Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

Initialize the Python SDK

How to initialize the Optimizely Feature Experimentation Python SDK in your application.

Instantiate Optimizely class to initialize the Python SDK and create an instance of the Optimizely client that exposes API methods like the Decide methods. 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 set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

The table below lists the required and optional parameters in Python.

ParameterTypeDescription
datafile
optional
stringThe JSON string representing the project.
Must provide either datafile or sdk_key.
sdk_key
optional
stringOptional string that uniquely identifies the datafile corresponding to project and environment combination.
Must provide either datafile or sdk_key.
event_dispatcher
optional
EventDispatcherAn event handler to manage network calls.
logger
optional
logging.LoggerA logger implementation to log issues.
error_handler
optional
BaseErrorHandlerAn error handler object to handle errors. --comment can you just say "an object to handle errors"?
user_profile_service
optional
UserProfileServiceA user profile service.
skip_json_validation
optional
BooleanSpecifies whether the JSON should be validated. Set to true to skip JSON validation on the schema, or false to perform validation.
config_manager
optional
BaseConfigManagerImplements optimizely.config_manager.BaseConfigManager.
Responsible for providing get_config method which returns an instance of optimizely.project_config.ProjectConfig.
notification_center
optional
NotificationCenterInstance 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.
datafile_access_token
optional
string(Server-side only) An access token for Optimizely Feature Experimentation SDKs (in combination with an SDK key) 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.
default_decide_options
optional
arrayAn 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 overrides defaults).
For details on decide options, see OptimizelyDecideOption
event_processor_options
optional
dictionaryA dictionary of options to pass to the default batch event processor. See BatchEventProcessor for more details.
settings
optional
OptimizelySdkSettingsInstance of optimizely.helpers.sdk_settings.OptimizelySdkSettings used to configure Advanced Audience Targeting.

The Python SDK enables the Advanced Audience Targeting methods by default. But, the methods do nothing unless you have enabled and configured the Advanced Audience Targeting integration.

To optionally disable Advanced Audience Targeting, setodp_disabled=True, see OdpManager.

Returns

Instantiates an instance of the Optimizely Feature Experimentation class.

Examples

In the Python SDK, you can provide either 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)

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

Include sdk_key as a string when you instantiate 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.

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 versions of the datafile. 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 or error handler for your specific requirements.

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:

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

OdpManager

👍

Beta

Advanced Audience Targeting is in beta. Apply on the Optimizely beta signup page or contact your Customer Success Manager.

OdpManager contains all the logic supporting Advanced Audience Targeting-related features, including audience segments.

The Ruby SDK enables the Advanced Audience Targeting methods by default. But, the methods do nothing unless you have enabled and configured the Advanced Audience Targeting integration.

If necessary, to disable Advanced Audience Targeting altogether, set odp_disabled: True. See the following sample code for more 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 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.

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).

📘

Note

Although the Python SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors), completion is not guaranteed.

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.

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.

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 custom request_timeout and flush_interval in the initializer. If set to zero, the batch_size is 1; otherwise, batch_size is set to the default of 10.

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

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)

Providing a custom cache

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

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

Here is an example of custom cache implementation:

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:

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. --comment passive voice

Use authenticated datafiles in secure environments

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

To use an authenticated datafile, download your Optimizely Feature Experimentation environment's access token from the Optimizely app at Settings>Environments. Select your secure environment, and copy the Datafile access token. The example below 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.

# 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 more information on the custom use of the Optimizely Feature Experimentation datafile, see Manage config (datafile).

Source files

The language and platform source files containing the implementation for Python are available on GitHub.