Skip to main content

Python Server SDK

Installation

pip install statsig-python-core

Initialize the SDK

After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.

info

Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.

There is also an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.
from statsig_python_core import Statsig, StatsigOptions # note, import statement has underscores while install has dashes

options = StatsigOptions()
options.environment = "development"

statsig = Statsig("secret-key", options)
statsig.initialize().wait()

# If you're running this in a script, be sure to wait for shutdown at the end to flush event logs to statsig
statsig.shutdown().wait()
initialize will perform a network request. After initialize completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.

Working with the SDK

Checking a Feature Flag/Gate

Now that your SDK is initialized, let's fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.

From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:

user = StatsigUser("a-user")

if statsig.check_gate(user, "a_gate"):
# Gate is on, enable new feature
else:
# Gate is off

Reading a Dynamic Config

Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:

# Get a dynamic config for a specific user
config = statsig.get_dynamic_config(StatsigUser("my_user"), "a_config")

# Access config values with type-safe getters and fallback values
product_name = config.get_string("product_name", "Awesome Product v1") # returns String
price = config.get_float("price", 10.0) # returns float
should_discount = config.get_boolean("discount", False) # returns bool
quantity = config.get_integer("quantity", 1) # returns int64

# Advanced Usage:
# You can disable exposure logging for this specific check
options = DynamicConfigEvaluationOptions(disable_exposure_logging=True)
config = statsig.get_dynamic_config(user, "a_config", options)

# The config object also provides metadata about the evaluation
print(config.rule_id) # The ID of the rule that served this config
print(config.id_type) # The type of the evaluation (experiment, config, etc)

The get_dynamic_config() method returns a DynamicConfig object that allows you to:

  • Fetch typed values with fallback defaults using get_string(), get_float(), get_boolean(), and get_integer()
  • Access evaluation metadata through properties like rule_id and id_type
  • Configure evaluation behavior using DynamicConfigEvaluationOptions

By default, Statsig logs exposures automatically when configs are evaluated. You can disable this for specific checks using the evaluation options.

Getting a Layer/Experiment

Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker iterations with parameter reuse.

# Values via get_layer
layer = statsig.get_layer(StatsigUser("my_user"), "user_promo_experiments")
title = layer.get_string("title", "Welcome to Statsig!")
discount = layer.get_float("discount", 0.1)

# Via get_experiment
title_exp = statsig.get_experiment(StatsigUser("my_user"), "new_user_promo_title")
price_exp = statsig.get_experiment(StatsigUser("my_user"), "new_user_promo_price")

title = title_exp.get_string("title", "Welcome to Statsig!")
discount = price_exp.get_float("discount", 0.1)

Parameter Stores

Parameter stores are not yet available for this sdk. Need it now? Let us know in Slack.

Logging an Event

Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:

statsig.log_event(
user=StatsigUser("user_id"), # Replace with your user object
event_name="add_to_cart",
value="SKU_12345",
metadata={
"price": "9.99",
"item_name": "diet_coke_48_pack"
}
)

Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.

Retrieving Feature Gate Metadata

In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object:

gate = statsig.get_feature_gate(user, "example_gate");
print(gate.rule_id)
print(gate.value)

Manual Exposures

warning

Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.

Manual exposures give you the option to query your gates/experiments without triggering an exposure, and optionally, manually log the exposure after the fact.

To check a gate without an exposure being logged, call the following.

result = statsig.check_gate(aUser, 'a_gate_name', FeatureGateEvaluationOptions(disable_exposure_logging=True))

Later, if you would like to expose this gate, you can call the following.

statsig.manually_log_gate_exposure(aUser, 'a_gate_name')

Statsig User

When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)

Besides userID, we also have email, ip, userAgent, country, locale and appVersion as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom field and be able to create targeting based on them.

note

Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.

Note that while typing is lenient on the StatsigUser object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.

user = StatsigUser(
user_id="123",
email="testuser@statsig.com",
ip="192.168.1.101",
user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36",
country="US",
locale="en_US",
app_version="4.3.0",
custom={"cohort": "June 2021"},
private_attributes={"gender": "female"},
)

Private Attributes

Have sensitive user PII data that should not be logged? No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.

For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user and that's it!

Statsig Options

StatsigOptions Class

The statsig.initialize() method takes an optional parameter options to customize the Statsig client. Below is the structure of the StatsigOptions class, including available parameters and their descriptions:

Parameters

  • specs_url: Optional[str]
    Custom URL for fetching feature specifications.

  • specs_sync_interval_ms: Optional[int]
    How often the SDK updates specifications from Statsig servers (in milliseconds).

  • init_timeout_ms: Optional[int]
    Sets the maximum timeout for initialization requests (in milliseconds).

  • log_event_url: Optional[str]
    Custom URL for logging events.

  • disable_all_logging: Optional[bool]
    When true, disables all event logging.

  • disable_network: Optional[bool] When true, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called "localMode".

  • event_logging_flush_interval_ms: Optional[int]
    How often events are flushed to Statsig servers (in milliseconds).

  • event_logging_max_queue_size: Optional[int]
    Maximum number of events to queue before forcing a flush.

  • enable_id_lists: Optional[bool]
    Enable/disable ID list functionality.

  • disable_user_agent_parsing Optional[bool] Default false. If set to true, the SDK will NOT attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation.

  • wait_for_user_agent_init Optional[bool] Default: false

    When set to true, the SDK will wait until user agent parsing data is fully loaded during initialization. This may slow down by ~1 second startup but ensures that parsing of the user’s userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations.

  • disable_user_country_lookup Optional[bool] Default false. If set to true, the SDK will NOT attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation.

  • wait_for_country_lookup_init Optional[bool] Default: false

    When set to true, the SDK will wait for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down by ~1 second startup but ensures that IP-to-country parsing is ready at evaluation time

  • id_lists_url: Optional[str]
    Custom URL for fetching ID lists.

  • id_lists_sync_interval_ms: Optional[int]
    How often the SDK updates ID lists from Statsig servers (in milliseconds).

  • fallback_to_statsig_api: Optional[bool]
    Whether to fallback to the Statsig API if custom endpoints fail.

  • environment: Optional[str]
    Environment parameter for evaluation.

  • output_log_level: Optional[str]
    Controls the verbosity of SDK logs.

  • persistent_storage: Optional[PersistentStorageBaseClass]
    Adapter / Interface to use persistent assignment within SDK. More details


Example Usage

from statsig_python_core import StatsigOptions

# Initialize StatsigOptions with custom parameters
options = StatsigOptions()
options.environment = "development"
options.init_timeout_ms = 3000
options.disable_all_logging = False

# Pass the options object into statsig.initialize()
statsig = Statsig("secret-key", options)
statsig.initialize().wait()

Shutting Statsig Down

Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.

To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:

statsig.shutdown().wait()

Local Overrides

To override the return value of a gate/config/experiment/layer locally, we expose a set of override APIs. Coupling this with StatsigOptions.disable_network can be helpful when writing unit tests.

// Overrides the given gate to the specified value
statsig.override_gate("a_gate_name", true)

// Overrides the given dynamic config to the provided value
statsig.override_dynamic_config("a_config_name", { "key": "value" })

// Overrides the given experiment to the provided value
statsig.override_experiment("an_experiment_name", { "key": "value" })

// Overrides the given layer to the provided value
statsig.override_layer("a_layer_name", { "key": "value" })

// Overrides the given experiment to a particular groupname, available for experiments only:
statsig.override_experiment_by_group_name("an_experiment_name", "a_group_name")
note
  1. These only apply locally - they do not update definitions in the Statsig console or elsewhere.
  2. The local override API is not designed to be a full mock. They are only a convenient way to override the value of the gate/config/etc.

Server Core

Statsig Server Core is a performance-focused rewrite of our server SDKs with a shared, core Rust library. With extensive optimization and Rust's inherent speed, Core SDKs can evaluate 5-10x as fast as our native SDKs.

Server Core also introduces new features, like Parameter Stores, the SDK Observability Interface, and streaming flag/experiment changes (from the Statsig Forward Proxy)

Server Core is currently available for Java, Node, Elixir, Rust and Python. Need another language, or run into any issues? Let us know in the Statsig Slack and we'll prioritize it.

FAQ

How do I run experiments for logged out users?

See the guide on device level experiments