Optimizely Python SDK
The Optimizely Python SDK enables developers to integrate Optimizely Feature Experimentation, Optimizely Full Stack (legacy), and Optimizely Rollouts into their Python applications. It allows for server-side A/B testing, feature flagging, and personalization. The library is actively maintained with regular releases, currently at version 5.4.0.
Warnings
- breaking Version 5.0.0 introduced significant new features, notably the integration with Optimizely Data Platform (ODP) for Advanced Audience Targeting. While core API signatures might not have changed universally, this release impacts how audiences are defined, how user attributes are processed, and potentially requires a re-evaluation of your experimentation strategy and data integration if you leverage advanced targeting.
- gotcha In version 5.0.1, the `pyOpenSSL` and `cryptography` dependencies were removed. This change reduces dependency bloat, but applications that implicitly relied on `optimizely-sdk` to install these for other unrelated purposes may encounter `ModuleNotFoundError`.
- gotcha The SDK requires an Optimizely datafile as a JSON string for initialization. Managing the fetching, caching, and refreshing of this datafile is critical for performance and ensuring experiments are up-to-date. The SDK provides mechanisms but does not automatically handle all aspects of persistence or complex caching.
- gotcha Version 5.4.0 includes fixes for impression event handling and global holdout implementation. These changes correct how events are dispatched and how users assigned to a global holdout are processed, which could subtly alter collected experiment data or user assignment behavior if your system was inadvertently relying on previous, potentially incorrect, logic.
Install
-
pip install optimizely-sdk
Imports
- Optimizely
from optimizely import Optimizely
Quickstart
import os
from optimizely import Optimizely
# The Optimizely datafile is a JSON string describing your experiments and features.
# In a real application, you would typically fetch this from Optimizely's CDN
# or use a dedicated datafile manager. For this example, we'll use an environment
# variable or a minimal placeholder.
# Replace 'YOUR_OPTIMIZELY_DATAFILE_JSON_HERE' with your actual datafile content.
# A minimal valid datafile for testing might look like:
# '{"version": "4", "revision": "1", "projectId": "123", "experiments": [], "featureFlags": []}'
datafile_json = os.environ.get(
'OPTIMIZELY_DATAFILE',
'{"version": "4", "revision": "1", "projectId": "123", "experiments": [], "featureFlags": []}'
)
# Initialize the Optimizely client
# Consider using an event dispatcher and logger for production environments.
optimizely_client = Optimizely(datafile_json=datafile_json)
# Example: Check if a feature flag is enabled for a user
user_id = "user_xyz"
user_attributes = {"browser_type": "chrome", "plan_type": "premium"}
feature_key = "example_feature"
if optimizely_client.is_feature_enabled(feature_key, user_id, user_attributes):
print(f"Feature '{feature_key}' is ENABLED for user '{user_id}'.")
else:
print(f"Feature '{feature_key}' is DISABLED for user '{user_id}'.")
# Example: Decide on a flag and get its variables
flag_key = "new_ui_variant"
decision = optimizely_client.decide(flag_key, user_id, user_attributes)
print(f"\nDecision for flag '{flag_key}':")
print(f" Variation Key: {decision.variation_key}")
print(f" Enabled: {decision.enabled}")
print(f" Variables: {decision.variables}")
print(f" Reasons: {decision.reasons}")
# Example: Track a conversion event
event_key = "purchase_complete"
event_tags = {"revenue": 49.99, "currency": "USD"}
optimizely_client.track(event_key, user_id, user_attributes, event_tags)
print(f"\nTracked event '{event_key}' for user '{user_id}'.")
# It's important to close the client to ensure background threads are terminated cleanly.
optimizely_client.close()
print("\nOptimizely client closed.")