Amplitude Experiment Python SDK

1.10.1 · active · verified Thu Apr 16

The `amplitude-experiment` library is the official Amplitude Experiment Python SDK for server-side instrumentation, enabling feature flagging and A/B testing. It supports both remote and local evaluation of feature flags. The current version is 1.10.1 and the library maintains an active development cycle with frequent updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Amplitude Experiment client for remote evaluation, define a user, fetch feature flag variants, and access a specific flag's value. The API key should be a server-side deployment key. For local evaluation, use `Experiment.initialize_local()` and `experiment.start()` followed by `experiment.evaluate()`.

import os
from amplitude_experiment import Experiment, User

# Get your deployment's API key from environment variables
API_KEY = os.environ.get('AMPLITUDE_EXPERIMENT_API_KEY', 'YOUR_DEPLOYMENT_KEY')

# Initialize the experiment remote evaluation client
# It's recommended to initialize the client once on application startup.
experiment = Experiment.initialize_remote(API_KEY)

# Define a user for whom variants should be fetched
user = User(
    device_id="abcdefg",
    user_id="user@company.com",
    user_properties={'premium': True, 'country': 'USA'}
)

async def get_variants_and_evaluate():
    try:
        # Fetch variants for the user asynchronously
        variants = await experiment.fetch_v2(user)

        # Access a flag's variant
        feature_flag_key = 'your-feature-flag-key'
        variant = variants.get(feature_flag_key)

        if variant:
            print(f"Variant for '{feature_flag_key}': {variant.value}")
            if variant.value == 'on':
                # Implement 'on' behavior
                print("Feature is ON for this user.")
            elif variant.value == 'control':
                # Implement 'control' behavior
                print("User is in control group.")
            else:
                # Implement other variant behavior
                print(f"User is in variant: {variant.value}")
        else:
            print(f"Flag '{feature_flag_key}' not found or variant is None.")

    except Exception as e:
        print(f"An error occurred: {e}")

# In a real application, you would call get_variants_and_evaluate() 
# within an async context, e.g., using asyncio.run()
# import asyncio
# asyncio.run(get_variants_and_evaluate())

view raw JSON →