> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK reference

<View title="Developer" />

<View title="Federal docs" />

<View title="EU docs" />

This topic documents how to get started with the Python SDK, and links to reference information on all of the supported features.

<Note>
  **SDK quick links**

  LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and sample applications:

  <table>
    <thead>
      <tr>
        <th>Resource</th>
        <th>Location</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>SDK API documentation</td>
        <td>[SDK API docs](https://launchdarkly-python-sdk.readthedocs.io/)</td>
      </tr>

      <tr>
        <td>Supported SDK Versions</td>
        <td>[Python server SDK](/docs/sdk/concepts/supported-versions#python-server-sdk)</td>
      </tr>

      <tr>
        <td>GitHub repository</td>
        <td>[python-server-sdk](https://github.com/launchdarkly/python-server-sdk)</td>
      </tr>

      <tr>
        <td>Sample applications</td>
        <td>[Python](https://github.com/launchdarkly/hello-python)<br /> [R](https://github.com/launchdarkly/hello-r)</td>
      </tr>

      <tr>
        <td>Published module</td>
        <td>[PyPI](https://pypi.org/project/launchdarkly-server-sdk/)</td>
      </tr>
    </tbody>
  </table>
</Note>

<Note>
  **SDK version compatibility**

  The LaunchDarkly Python SDK, version 9.0 through 9.11, is compatible with Python 3.8.0 and higher. Starting with version 9.12, the SDK requires Python 3.9.0 or higher.
</Note>

## Get started

After you complete the [Getting Started process](/docs/home/getting-started), follow these instructions to start using the LaunchDarkly SDK in your Python application.

### Install the SDK

First, install the LaunchDarkly SDK as a dependency in your application using your application's dependency manager. If you want to depend on a specific version, refer to the [SDK releases page](https://github.com/launchdarkly/python-server-sdk/releases) to identify the latest version.

We recommend making the LaunchDarkly [observability plugin](/docs/sdk/observability) available as well. This plugin collects and sends observability data to LaunchDarkly, including [metrics autogenerated from OpenTelemetry data](/docs/home/metrics/autogen/opentelemetry). This means you can review error monitoring, logs, and traces from within the LaunchDarkly UI. They require the Python SDK version 9.12 or later.

<Warning>
  **Asynchronous support is experimental**

  `AsyncLDClient` is experimental. It is not recommended for production use, its API may change between releases, and it is not subject to backward-compatibility guarantees. Pin to a specific minor version, and review the changelog before you upgrade.

  This does not affect the synchronous `LDClient`, which is fully supported for production use.
</Warning>

Here's how:

<CodeGroup>
  ```bash title="Shell" lines wrap theme={null}
  pip install launchdarkly-server-sdk

  # optional observability plugin, requires Python SDK v9.12+
  pip install launchdarkly-observability
  ```

  ```bash title="Shell (async)" lines wrap theme={null}
  pip install launchdarkly-server-sdk[async]
  ```
</CodeGroup>

Next, import the LaunchDarkly client in your application code:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  import ldclient
  from ldclient.config import Config

  # optional observability plugin, requires Python SDK v9.12+
  import ldobserve
  from ldobserve import ObservabilityConfig, ObservabilityPlugin, observe
  ```

  ```python title="Python (async)" lines wrap theme={null}
  from ldclient.async_client import AsyncLDClient
  from ldclient.async_config import AsyncConfig
  ```
</CodeGroup>

<Note>
  **The Python SDK uses an SDK key**

  The Python SDK uses an SDK key. Keys are specific to each project and environment. They are available on the **SDK keys** page under **Settings**. To learn more about key types, read [Keys](/docs/sdk/concepts/client-side-server-side#keys-and-credentials).
</Note>

### Initialize the client

After you install and import the SDK, create a single, shared instance of `ldclient`. Specify your SDK key here to authorize your application to connect to a particular environment within LaunchDarkly.

The `get()` function enforces the singleton pattern. You should only have one instance of the client in your application.

<Warning>
  **ldclient must be a singleton**

  It's important to make `ldclient` a singleton for each LaunchDarkly project. The client instance maintains internal state that allows LaunchDarkly to serve feature flags without making any remote requests. Do not instantiate a new client with every request.

  If you have multiple LaunchDarkly projects, you can create one `LDClient` for each. In this situation, the clients operate independently. For example, they do not share a single connection to LaunchDarkly.
</Warning>

Only create one instance of `client`.

Here's how:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  ldclient.set_config(Config("YOUR_SDK_KEY",
    # optional observability plugin, requires Python SDK v9.12+
    plugins=[ObservabilityPlugin()]
    )
  )
  client = ldclient.get()
  ```

  ```python title="Python (async)" lines wrap theme={null}
  client = AsyncLDClient(AsyncConfig("YOUR_SDK_KEY"))
  await client.start()

  # Or let the context manager start and close the client for you:
  #   async with AsyncLDClient(AsyncConfig("YOUR_SDK_KEY")) as client:
  #       ...
  ```
</CodeGroup>

<Warning>
  **Worker-based servers require specific setup**

  The Python SDK uses multiple background threads to operate correctly. If the SDK is deployed to an environment which forks from the main process, the SDK may not operate as expected. To learn more about this problem and how to fix it, refer to [Considerations with worker-based servers](#considerations-with-worker-based-servers), below.
</Warning>

### Evaluate a context

You can use `client` to check which variation a particular context will receive for a given feature flag. To learn more, read [Flag variation evaluation](/docs/sdk/features/evaluating) and [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons). For more information about how contexts are specified, read [Context configuration](/docs/sdk/features/context-config).

In the v8.0 example, the context key is the string "example-context-key". In the v7.x example, the user key is the string "example-user-key":

<CodeGroup>
  ```python title="Python SDK v8.0+" lines wrap theme={null}
  from ldclient import Context

  context = Context.builder("example-context-key").name("Sandy").build()
  flag_value = client.variation("example-flag-key", context, False)

  if flag_value:
      # application code to show the feature
      pass
  else:
      # the code to run if the feature is off
      pass
  ```

  ```python title="Python (async)" lines wrap theme={null}
  from ldclient import Context

  context = Context.builder("example-context-key").name("Sandy").build()
  flag_value = await client.variation("example-flag-key", context, False)

  if flag_value:
      # application code to show the feature
      pass
  else:
      # the code to run if the feature is off
      pass
  ```
</CodeGroup>

## Considerations with worker-based servers

The LaunchDarkly SDK relies on multiple threads to operate correctly. These threads provide essential functionality, including delivering flag updates and sending event data.

If the main process which instantiated the SDK is itself forked, the SDK will still evaluate flags, but it will be unable to receive changes to those flags in that child process. This is because threads do not survive the forking process in Python.

The good news is the LaunchDarkly SDK *is* compatible with worker-based servers. However, there are a few considerations:

* You should initialize a new client before the forking process.
* After you have forked the worker process, you can call `postfork()` to reinitialize the client. This way, your client will accurately reflect flag changes in the forked thread.

Here's how:

<CodeGroup>
  ```python title="Python SDK v9.11+" lines wrap theme={null}
  # 1. Create the client before forking.
  ldclient.set_config(Config("YOUR_SDK_KEY"))
  client = ldclient.get()

  # 2. From the newly forked process, reinitialize the client by calling `postfork`.
  # Examples for specific servers are shown below.
  client.postfork()
  ```
</CodeGroup>

Any configuration that you provide to the SDK must survive the forking process independently. We recommend that you add any [listeners](/docs/sdk/features/monitoring#python) or [hooks](/docs/sdk/features/hooks#python) after the `postfork()` call, unless you are certain they can survive the forking process.

If you are using the [Relay Proxy](/docs/sdk/relay-proxy), you must use Relay Proxy v8.11 or later to use `postfork()`.

To learn more about the specific configuration options available in this SDK, read [`ldclient.config`](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-main.html#module-ldclient.config). To learn more about the `postfork()` reinitialization, read [`ldclient.postfork`](https://launchdarkly-python-sdk.readthedocs.io/en/latest/api-main.html#ldclient.client.LDClient.postfork).

### Example: Configure uWSGI

In uWSGI environments, you must set the `enable-threads` option. After `uwsgi` has forked the worker process, you can call `postfork()` to reinitialize the client. You can do this using `uwsgidecorators`.

Here's how:

<CodeGroup>
  ```python title="Python uWSGI initialization" lines wrap theme={null}
  import uwsgidecorators

  # Instantiate the client before the fork
  ldclient.set_config(LDConfig("YOUR_SDK_KEY"))
  client = ldclient.get()

  @uwsgidecorators.postfork
  def post_fork_client_initialization():
      # Reinitialize the client after the fork
      ldclient.get().postfork()

  ```
</CodeGroup>

### Asynchronous client

`AsyncLDClient` owns no background threads. It runs on the event loop of the process that uses it. You can create the client once, before the application forks or preloads its workers, because its constructor does not require a running event loop. You then start it on each worker's own event loop with `await client.start()`. This means the async client does not need a `postfork()` step.

This model fits Asynchronous Server Gateway Interface (ASGI) servers. Create the client at application startup, then start it in the server's lifespan handler. To learn more about the async client's current limitations, read the [async support notes](https://github.com/launchdarkly/python-server-sdk#async-support).

## HTTPS proxy

Python's standard HTTP library provides a built-in HTTPS proxy. If the HTTPS\_PROXY environment variable is present, then the SDK will proxy all network requests through the URL provided.

Here's how to set the HTTPS\_PROXY environment variable on Mac/Linux systems:

<CodeGroup>
  ```bash title="Shell" lines wrap theme={null}
  export HTTPS_PROXY=https://web-proxy.domain.com:8080
  ```
</CodeGroup>

Here's how to set the HTTPS\_PROXY environment variable on Windows systems:

<CodeGroup>
  ```bash title="cmd" lines wrap theme={null}
  set HTTPS_PROXY=https://web-proxy.domain.com:8080
  ```
</CodeGroup>

Here's how to set the HTTPS\_PROXY environment variable from within Python:

<CodeGroup>
  ```python title="Python" lines wrap theme={null}
  os.environ["HTTPS_PROXY"] = "https://web-proxy.domain.com:8080"
  ```
</CodeGroup>

## Shut down the client

Shut down the client when your application terminates. To learn more, read [Shutting down](/docs/sdk/features/shutdown#python).

## Supported features

This SDK supports the following features:

* [SDK configuration](/docs/sdk/features/config#python), including
  * [Application metadata configuration](/docs/sdk/features/app-config#python)
  * [Migration configuration](/docs/sdk/features/migration-config#python)
  * [Service endpoint configuration](/docs/sdk/features/service-endpoint-configuration#python)
* [Anonymous contexts and users](/docs/sdk/features/anonymous#python)
* [Big segments](/docs/sdk/features/big-segments#python)
* [Context configuration](/docs/sdk/features/context-config#python)
* [Data saving mode](/docs/sdk/features/data-saving-mode#python)
* [Flag variation evaluation](/docs/sdk/features/evaluating#python)
* [Flag variation evaluation details](/docs/sdk/features/evaluation-reasons#python)
* [Flushing events](/docs/sdk/features/flush#python)
* [Getting all flags](/docs/sdk/features/all-flags#python)
* [Hooks](/docs/sdk/features/hooks#python)
* [Identifying and changing contexts](/docs/sdk/features/identify#python)
* [Logging configuration](/docs/sdk/features/logging#python)
* [Migrations](/docs/sdk/features/migrations#python)
* [Monitoring SDK status](/docs/sdk/features/monitoring#python)
* [Observability](/docs/sdk/observability/python)
* [Offline mode](/docs/sdk/features/offline-mode#python)
* [OpenTelemetry](/docs/sdk/features/opentelemetry-server-side#python)
* [Private attributes](/docs/sdk/features/private-attributes#python)
* [Reading flags from a file](/docs/sdk/features/flags-from-files#python)
* [Relay Proxy configuration](/docs/sdk/features/relay-proxy-configuration)
  * [Using proxy mode](/docs/sdk/features/relay-proxy-configuration/proxy-mode#python)
  * [Using daemon mode](/docs/sdk/features/relay-proxy-configuration/daemon-mode#python)
* [Secure mode](/docs/sdk/features/secure-mode#python)
* [Tracking custom events](/docs/sdk/features/events#python)
* [Shutting down](/docs/sdk/features/shutdown#python)
* [Storing data](/docs/sdk/features/storing-data#python)
* [Subscribing to flag changes](/docs/sdk/features/flag-changes#python)
* [Test data sources](/docs/sdk/features/test-data-sources#python)
* [Web proxy configuration](/docs/sdk/features/web-proxy#python)
