Optimizely Python SDK

5.4.0 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Optimizely client, check the status of a feature flag, make a decision on an experiment flag, and track a conversion event. It's crucial to provide a valid `datafile_json` and manage the client's lifecycle, including calling `close()` when it's no longer needed.

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

view raw JSON →