GrowthBook Python SDK

2.2.0 · active · verified Sat Apr 11

GrowthBook is a Python SDK for powerful feature flagging and A/B testing in Python applications. It enables local evaluation of feature flags and experiments, flexible targeting, and integration with existing event tracking systems. The library is lightweight, fast, and supports both synchronous and asynchronous usage. As of version 2.2.0, it is actively maintained with frequent releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize and use the `GrowthBookClient` for asynchronous applications, fetch feature flags, check feature status, retrieve feature values, and run A/B experiments. It uses environment variables for `client_key` and `api_host` for secure and flexible configuration. The `GrowthBookClient` is recommended for performance and resource utilization in async environments.

import asyncio
import os
from growthbook import GrowthBookClient, Options, UserContext, FeatureRefreshStrategy

async def main():
    # Get client key from environment variable for security
    client_key = os.environ.get("GROWTHBOOK_CLIENT_KEY", "sdk-YOUR_CLIENT_KEY")
    api_host = os.environ.get("GROWTHBOOK_API_HOST", "https://cdn.growthbook.io")

    # User attributes for targeting and experimentation
    attributes = {
        "id": "user-123",
        "country": "US",
        "loggedIn": True
    }

    # Configure GrowthBook client options
    options = Options(
        api_host=api_host,
        client_key=client_key,
        # Optional: Enable real-time feature updates via Server-Sent Events (SSE)
        refresh_strategy=FeatureRefreshStrategy.SERVER_SENT_EVENTS
    )

    # Create a UserContext instance
    user_context = UserContext(attributes=attributes)

    # Create an async GrowthBookClient instance (recommended for async apps)
    async with GrowthBookClient(options=options, user_context=user_context) as gb:
        # Load features from the GrowthBook API
        await gb.load_features()

        # Simple on/off feature gating
        if gb.is_on("my-awesome-feature"): # Replace with your feature key
            print("My awesome feature is ON!")
        else:
            print("My awesome feature is OFF.")

        # Get the value of a feature with a fallback
        button_color = gb.get_feature_value("button-color-feature", "blue") # Replace with your feature key
        print(f"Button color feature value: {button_color}")

        # Example for an experiment
        # Make sure 'pricing-experiment' and variations are configured in GrowthBook
        pricing_result = gb.run(
            {
                "key": "pricing-experiment",
                "variations": ["control", "variant-a", "variant-b"]
            }
        )

        if pricing_result.in_experiment:
            print(f"User in pricing experiment, assigned variation: {pricing_result.value}")
        else:
            print("User not in pricing experiment.")

    print("GrowthBook client closed.")

if __name__ == "__main__":
    # Set dummy keys for local testing, replace with actual keys or environment variables
    os.environ["GROWTHBOOK_CLIENT_KEY"] = "sdk-example12345"
    os.environ["GROWTHBOOK_API_HOST"] = "https://cdn.growthbook.io"
    asyncio.run(main())

view raw JSON →