---
title: Initialize the Python SDK
slug: feature-experimentation/docs/initialize-sdk-python
docTags: 
createdAt: 2026-08-05T20:40:01.000Z
---

Instantiate `Optimizely` class to initialize the Python SDK and create an instance of the Optimizely client that exposes API methods like the [Decide methods](docId\:i0YJZkiaylg7J6QKk3GR_). Each client corresponds to the datafile representing the state of a project for a certain environment.

## Version

5.0.0

## Description

The SDK provides a default implementation, but you may want to override optional parameters for your production environments. For example, you can override the parameters to configure an [error handler](docId\:OYJFKN4hBizOxbwGWK_2d) and [logger](docId:2TxOfXS_LSJoRL6KE-Ro4) to catch issues, an [event dispatcher](docId\:TRCoMkvqjO8ghdWnEFDMW) to manage network calls, and a [User Profile Service](docId\:E-dn78U8CI51eFxyzn8T3) to ensure sticky bucketing.

## Parameters

The following are the required and optional parameters in Python:

| Parameter                                  | Type                      | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------------------------------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \`datafile\` \_optional\_                  | string                    | The JSON string representing the project. You can provide either \`datafile\` or \`sdk\_key\` or both. See the \[Examples]\(#examples) section.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| \`sdk\_key\` \_optional\_                  | string                    | Optional string that uniquely identifies the datafile corresponding to project and environment combination. You can provide either \`datafile\` or \`sdk\_key\` or both. See the \[Examples]\(#examples) section.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| \`event\_dispatcher\` \_optional\_         | EventDispatcher           | An event handler to manage network calls.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| \`logger\` \_optional\_                    | logging.Logger            | A logger implementation to log issues.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| \`error\_handler\` \_optional\_            | BaseErrorHandler          | An object to handle errors.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| \`user\_profile\_service\` \_optional\_    | UserProfileService        | A user profile service.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| \`skip\_json\_validation\` \_optional\_    | Boolean                   | Specifies whether the JSON should be validated. Set to \`true\` to skip JSON validation on the schema, or \`false\` to perform validation.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| \`config\_manager\` \_optional\_           | BaseConfigManager         | Implements \`optimizely.config\_manager.BaseConfigManager\`. Responsible for providing \`get\_config\` method which returns an instance of \`optimizely.project\_config.ProjectConfig\`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| \`notification\_center\` \_optional\_      | NotificationCenter        | Instance of \`optimizely.notification\_center.NotificationCenter\`. This option is useful when providing your own \`optimizely.config\_manager.BaseConfigManager\` implementation, which can use the same NotificationCenter instance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| \`access\_tkn\` \_optional\_               | string                    | Use an access token (with an \`sdkKey\`) to fetch the datafile from an authenticated endpoint. Find your datafile access token in the Optimizely app at **Settings > Environments**. Select your secure environment, and copy the **Datafile access token**. See the \[Use authenticated datafile in a secure environment]\(#use-authenticated-datafile-in-a-secure-environment) section.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| \`default\_decide\_options\` \_optional\_  | array                     | An array of \`OptimizelyDecideOption\` enums. When the Optimizely client is constructed with this parameter, it sets default decide options which are applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not override defaults). For details on decide options, see \[OptimizelyDecideOption]\(https\://docs.developers.optimizely.com/feature-experimentation/docs/decide-methods-python#optimizely-decide-option).                                                                                                                                                                                                                                                                                                                                                                                                       |
| \`event\_processor\_options\` \_optional\_ | dictionary                | A dictionary of options to pass to the default batch event processor. See \[BatchEventProcessor]\(https\://docs.developers.optimizely.com/feature-experimentation/docs/event-batching-python#configure-event-batching) for more details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| \`settings\`                               | \`OptimizelySdkSettings\` | Instance of \`optimizely.helpers.sdk\_settings.OptimizelySdkSettings\` used to configure \[Real-Time Audiences for Feature Experimentation]\(https\://docs.developers.optimizely.com/feature-experimentation/docs/real-time-audiences-for-feature-experimentation). You must configure this parameter to use Real-Time Audiences for Feature Experimentation. The Python SDK enables the Real-Time Audiences for Feature Experimentation by default. But, the methods do nothing unless you have enabled and configured \[Real-Time Audiences for Feature Experimentation]\(https\://docs.developers.optimizely.com/feature-experimentation/docs/real-time-audiences-for-feature-experimentation). To optionally disable Real-Time Audiences for Feature Experimentation, set \`odp\_disabled=True\`. See \[OdpManager]\(https\://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-python#odpmanager). |

## Returns

Instantiates an instance of the Optimizely class.

## Examples

In the Python SDK, you can provide `sdkKey`, `datafile`, or both.

- **When initializing with the SDK key** – The SDK polls for datafile changes in the background at regular intervals.
- **When initializing with the datafile** -- The SDK does not poll for datafile changes in the background.
- **When initializing with both the SDK key and datafile** – The SDK uses the given datafile and starts polling for datafile changes in the background.

### Instantiate using SDK Key (recommended)

You only need to pass the SDK key value in the Python SDK to instantiate a client. Whenever the experiment configuration changes, the SDK handles the change for you.

Include `sdk_key` as a string when instantiating the `Optimizely` class.

When you provide the `sdk_key`, the SDK instance downloads the datafile associated with that `sdk_key`. When the download completes, the SDK instance updates itself to use the downloaded datafile.

```python
from optimizely import optimizely

optimizely_client = optimizely.Optimizely(sdk_key='123456')
```

### Instantiate using datafile

You can also instantiate with a hard-coded datafile. If you do not pass in an SDK key, the Optimizely Client will not automatically sync newer datafile versions. Any time you retrieve an updated datafile, just re-instantiate the same client.

To instantiate a client for simple applications, provide a datafile specifying the project configuration for a given environment. For most advanced implementations, you should [customize the logger](docId:2TxOfXS_LSJoRL6KE-Ro4) or [error handler](docId\:OYJFKN4hBizOxbwGWK_2d) for your specific requirements.

```python
from optimizely import optimizely

# Instantiate an Optimizely client
optimizely_client = optimizely.Optimizely(datafile)
```

## Notes

### Enable JSON schema validation

Skipping JSON schema validation enhances performance during instantiation. In the Python SDK, you can control whether to validate the JSON schema of the datafile when instantiating the client. This example shows how to skip JSON schema validation:

```python
# Skip JSON schema validation (SDK versions 0.1.1 and above)
optimizely_client = optimizely.Optimizely(datafile, skip_json_validation=True)
```

## Dispose of the client

For effective resource management with the Optimizely Python SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by calling `optimizelyClient.close()`.

The `.close()` method ensures that the processes and queues associated with the instance are properly released. This is essential for preventing memory leaks and ensuring that the application runs efficiently, especially in environments where resources are limited or in applications that create and dispose of many instances over their lifecycle.

## Use authenticated datafiles in secure environments

You can fetch the datafile from an authenticated endpoint using a server-side (only) Optimizely SDK, like the Python SDK.

To use an [authenticated datafile](docId\:YpSOMYlWkUccLCL-uB-ZE), download your environment's access token from the Optimizely app by going to **Settings > Environments**. Select your secure environment, and copy the **Datafile access token**. The following example shows how to initialize the Optimizely client using an access token and `sdk_key`, enabling the client to fetch the authenticated datafile and complete initialization.

```python
# fetch the datafile from an authenticated endpoint
access_tkn = 'YOUR_DATAFILE_ACCESS_TOKEN'
sdk_key = 'YOUR_SDK_KEY'
optimizely_client = optimizely.Optimizely(sdk_key = sdk_key, datafile_access_token = access_tkn )
```

For information on the custom use of the datafile, see  [Manage config (datafile)](docId:3LmHm4b3kTxKBuoR93KN8).

## `OdpManager`

The `OdpManager` contains all the logic supporting Real-Time Audiences for Feature Experimentation-related features, including audience segments. You must configure this parameter to use Real-Time Audiences for Feature Experimentation.

The Python SDK enables the Real-Time Audiences for Feature Experimentation methods by default. But, the methods do nothing unless you have enabled and configured [Real-Time Audiences for Feature Experimentation](docId:6UBBxxRv331nBIVZ2lun8).

:::hint{type="info"}
If necessary, to disable Real-Time Audiences for Feature Experimentation altogether, set `odp_disabled: True`. See the following sample code for information.
:::

### `OdpSegmentManager`

This module provides an interface to the remote ODP server for audience segment mappings.

It fetches all qualified segments for the given user context and returns true if the qualified segments array in the [user context](docId\:UGnzh86pPS0MtU91FSSlQ) was updated.

It also manages a segment's cache shared for all user contexts. The cache is in memory (not persistent) and is reset when the device is rebooted or the app is terminated.

The following settings are optionally configurable when the Python SDK is initialized:

- **ODP SegmentsCache size** – `segments_cache_size`
  - **Default** – 10,000
  - Set to 0 to disable caching.
- **ODP SegmentsCache timeout** (in seconds) – `segments_cache_timeout_in_secs`
  - **Default** – 600 secs (10 minutes)
  - Set to 0 to disable timeout (never expires).
- **ODP enable** – `odp_disabled`
  - **Default** – False (enabled)
  - The Python SDK returns or logs an `odpNotEnabled` error when ODP is disabled and its features are requested.

See the code example in [OdpEventManager](docId:3RNo0adSzdB2ndnj5I_WC).

### `OdpEventManager`

This module provides an interface to the remote ODP server for events.

It queues all pending events (persistent) and sends them (in batches of up to 10) to the ODP server when all resources are available, including network connection and ODP public key (in the SDK's datafile).

:::hint{type="info"}
Although the Python SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors), completion is not guaranteed.
:::

```python
from optimizely import optimizely
from optimizely.odp.odp_segment_manager import OdpSegmentManager
from optimizely.odp.odp_event_manager import OdpEventManager
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

segments_cache = CustomCache()
event_manager = OdpEventManager()
segments_manager = OdpSegmentManager()

sdk_settings = OptimizelySdkSettings(
    odp_disabled=False,
    segments_cache_size=10_000,
    segments_cache_timeout_in_secs=600,
    odp_segments_cache=segments_cache,
    odp_segment_manager=segments_manager,
    odp_event_manager=event_manager,
    odp_segment_request_timeout=10,
    odp_event_request_timeout=10,
    odp_event_flush_interval=1
)
optimizely_client = Optimizely(settings=sdk_settings)
```

### Customize `OdpSegmentApiManager`

You can provide an `OdpSegmentApiManager` for customization.

```python
from optimizely import optimizely
from optimizely.odp.odp_segment_manager import OdpSegmentManager
from optimizely.odp.odp_segment_api_manager import OdpSegmentApiManager
from optimizely.odp.lru_cache import LRUCache
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

segment_api_manager = OdpSegmentApiManager(timeout=10)
cache = LRUCache(cache_size=10_000, cache_timeout=600)
odp_segment_manager = OdpSegmentManager(segments_cache=cache, api_manager=segment_api_manager)
sdk_settings = OptimizelySdkSettings(odp_segment_manager=odp_segment_manager)

optimizely_client = optimizely.Optimizely(settings=sdk_settings)
```

### Customize `OdpEventApiManager`

You can provide an `OdpEventApiManager` for customization.

```python
from optimizely import optimizely
from optimizely.odp.odp_event_api_manager import OdpEventApiManager
from optimizely.odp.odp_event_manager import OdpEventManager
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

event_api_manager = OdpEventApiManager(timeout=10)
odp_event_manager = OdpEventManager(api_manager=event_api_manager, flush_interval=1)
sdk_settings = OptimizelySdkSettings(odp_event_manager=odp_event_manager)

optimizely_client = optimizely.Optimizely(settings=sdk_settings)
```

### Customize `OdpEventManager`

You can provide a custom `request_timeout` and `flush_interval` in the initializer. If set to 0, the `batch_size` is 1. Otherwise, `batch_size` is set to the default of 10.

```python
from optimizely import optimizely
from optimizely.odp.odp_event_manager import OdpEventManager
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

event_manager = OdpEventManager(request_timeout=10, flush_interval=1)
sdk_settings = OptimizelySdkSettings(odp_event_manager=event_manager)

optimizely_client = optimizely.Optimizely(settings=sdk_settings)
```

### `OdpSegmentManager`

```python
from optimizely import optimizely
from optimizely.odp.odp_segment_manager import OdpSegmentManager
from optimizely.odp.lru_cache import LRUCache
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

cache = LRUCache(cache_size=10_000, cache_timeout=600)

odp_segment_manager = OdpSegmentManager(segments_cache=cache, timeout=10)
sdk_settings = OptimizelySdkSettings(odp_segment_manager=odp_segment_manager)

optimizely_client = optimizely.Optimizely(settings=sdk_settings)
```

### Provide a custom cache

You can provide a custom cache to store the `fetch_qualified_segments` results by implementing the `OptimizelySegmentsCache` Protocol.

```python
class OptimizelySegmentsCache(Protocol):
    def save(self, key: str, value: list[str]) -> None: ...
    def lookup(self, key: str) -> Optional[list[str]]: ...
    def reset(self) -> None: ...
```

The following is an example of custom cache implementation:

```python
class CustomCache:
    def __init__(self):
        self.lock = threading.Lock()
        self.map = {}

    def save(self, key, value):
        with self.lock:
           self.map[key] = value

    def lookup(self, key):
        with self.lock:
            return self.map.get(key)

    def reset(self):
        with self.lock:
            self.map.clear()
```

Pass this `CustomCache` within `OptimizelySdkSettings` when instantiating the Optimizely client.

```python
from optimizely import optimizely
from optimizely.helpers.sdk_settings import OptimizelySdkSettings

segments_cache = CustomCache()
sdk_settings = OptimizelySdkSettings(odp_segments_cache=segments_cache)
optimizely_client = optimizely.Optimizely(settings=sdk_settings)
```

If `odp_segments_cache` is provided, `segments_cache_size` and `segments_cache_timeout_in_secs` parameters from `OptimizelySdkSettings` are ignored.

## CMAB configuration

Configure the caching behavior for Contextual Multi-Armed Bandit (CMAB) decisions at initialization time.

Use `OptimizelyFactory` class methods to configure CMAB caching *before* initializing your client.

## Parameters

| Parameter           | Method                         | Type    | Default                                                   | Description                                                                                                      |
| ------------------- | ------------------------------ | ------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Cache Size          | \`cmab\_cache\_size\`          | Integer | 10000                                                     | Maximum number of cached decisions                                                                               |
| Custom Cache        | \`cmab\_custom\_cache\`        | Cache   | None                                                      | Optional custom cache implementation. If not provided, uses built-in thread-safe LRU cache                       |
| Cache TTL           | \`cmab\_cache\_ttl\`           | Integer | 1800 seconds (30 minutes)                                 | Time-to-live for cache entries                                                                                   |
| Prediction Endpoint | \`cmab\_prediction\_endpoint\` | str     | \`"https\://prediction.cmab.optimizely.com/predict/\{}"\` | URL template for CMAB prediction API. The \`\{}\` placeholder is replaced with the rule ID. Useful for proxying. |

For configuration examples, cache behavior details, and runtime control options, see [Configure the CMAB cache for the Python SDK](docId:0iALeD-UPcLOJiqxzy-QL).

## Source files

The language and platform source files containing the implementation for Python are available on [GitHub](https://github.com/optimizely/python-sdk/blob/master/optimizely/optimizely.py).
