Statsig Python Core SDK

0.18.1 · active · verified Thu Apr 09

The Statsig Python Core SDK (`statsig-python-core`) provides server-side Python bindings for integrating Statsig's feature flagging, A/B testing, and experimentation platform into your applications. It enables evaluating feature gates, dynamic configs, and experiments, and logging exposures without requiring a client-side Statsig SDK. It's currently at version 0.18.1 and receives regular updates, typically aligning with feature releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Statsig server SDK, define a user, check a feature gate, retrieve dynamic configs and experiments, and properly shut down the SDK. Ensure you replace `YOUR_SERVER_SECRET_KEY_HERE` with your actual Statsig server secret key and adjust gate/config/experiment names.

import asyncio
import os
from statsig import StatsigServer

async def main():
    # Replace with your actual Server Secret Key, or set as STATSIG_SERVER_SECRET_KEY env var
    sdk_key = os.environ.get("STATSIG_SERVER_SECRET_KEY", "YOUR_SERVER_SECRET_KEY_HERE")

    if sdk_key == "YOUR_SERVER_SECRET_KEY_HERE":
        print("Please set your STATSIG_SERVER_SECRET_KEY environment variable or replace the placeholder.")
        return

    await StatsigServer.initialize(sdk_key)

    # Define a user object using a dictionary (StatsigUser class is deprecated)
    user = {
        "userID": "test-user-123",
        "email": "test@example.com",
        "custom": {"plan": "enterprise"}
    }

    # Check a feature gate
    if await StatsigServer.check_gate(user, "my_feature_gate"): # Replace with your gate name
        print("my_feature_gate is ON for this user!")
    else:
        print("my_feature_gate is OFF for this user.")

    # Get a dynamic config
    config = await StatsigServer.get_config(user, "my_dynamic_config") # Replace with your config name
    string_value = config.get("string_param", "default_string")
    int_value = config.get("int_param", 0)
    print(f"Config values: string_param={string_value}, int_param={int_value}")

    # Get an experiment
    experiment = await StatsigServer.get_experiment(user, "my_experiment") # Replace with your experiment name
    variant_value = experiment.get("variant_param", "control")
    print(f"Experiment variant: {variant_value}")

    # IMPORTANT: Call shutdown when your application exits to ensure metrics are flushed
    await StatsigServer.shutdown()

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →