Skip to content
FlagSwiftDocs

Python SDK

Background polling, thread-safe, standard library only.

Use this SDK in Django, Flask, FastAPI, workers and scripts. It downloads your environment's configuration, keeps it fresh on a background thread and evaluates every flag in memory, so a check never touches the network. For other backends see the Node.js, Go and PHP SDKs. Options and behaviour every SDK shares are on Options and behaviour.

At a glance#

Install
pip install flagswift
Requires
Python 3.8+
Key
Server key (fs_srv_)
Evaluates
Locally, in memory
Real-time updates
Yes
Works offline from
Snapshot file
Outcome analytics
Yes
Verified
Tested against shared vectors

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
pip install flagswift

It needs Python 3.8 or newer, uses only the standard library and ships type hints (py.typed).

Initialization#

You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. There is no default host. Keep the key on the server. Create one client at startup, call initialize(), and close() it on shutdown.

flags.py
import os
from flagswift import FlagSwift

flags = FlagSwift(
    api_key=os.environ["FLAGSWIFT_KEY"],       # fs_srv_ or fs_admin_ key with evaluation:read
    base_url="https://flags.example.com",       # required: your FlagSwift server
    environment="production",                   # only for project-wide keys
    fallbacks={"new-checkout": False},
    snapshot_path="/var/cache/myapp/flagswift.json",
    on_error=lambda err: print("flagswift:", err),
)

flags.initialize()   # fetches, then starts background polling. Never raises.

A context manager closes the client for you.

python
with FlagSwift(api_key=key, base_url=url) as flags:
    print(flags.is_enabled("new-checkout", "user-42"))

Startup never blocks for long

initialize() waits at most init_timeout (5 seconds) and returns even with no network. The fetch and the poller carry on in the background thread and apply the configuration as soon as one succeeds.

Connection options#

api_key and base_url are required. Everything else has a default.

Common arguments of FlagSwift
ArgumentTypeDescription
api_key, base_url*strA server or admin key and your server address. A mistake raises FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL.
environmentstrOnly for project-wide keys. Default: the FLAGSWIFT_ENVIRONMENT variable.
refresh_intervalfloatSeconds between checks for changes. Default 30. Zero turns polling off.
streamingboolKeep one real-time connection open so changes arrive within moments. Default False.
fallbacksdictFlag key to value, served for unknown flags and before anything loads.
snapshot_pathstrJSON file that keeps the last configuration across restarts.
bootstrapdictA payload to start from, such as flags.get_snapshot() you saved.
timeout, init_timeoutfloatSeconds. Default 5 each.
max_retriesintDefault 3.
auto_exposuresboolQueue an exposure on every single-flag read. Default False.
on_error, on_updatecallableCallbacks. Exceptions raised inside them are swallowed.

Check flags#

The user is an identifier string, a list of identifiers, or a dict with identifier or identifiers, account(s), device(s) and attributes. A flag the server does not know gives your fallbacks value, then False.

python
user = {"identifier": "user-42", "account": "acme", "attributes": {"plan": "pro"}}

if flags.is_enabled("new-checkout", user):
    render_new_checkout()
else:
    render_old_checkout()

# Your own default when the flag is not found.
beta = flags.is_enabled("beta-banner", user, fallback=True)

For the reason behind an answer, call evaluate. It returns a dict with enabled, reason and found, plus variant and value for multivariate flags.

python
result = flags.evaluate("new-checkout", user)
print(result["enabled"], result["reason"], result["found"])

Use it in a web framework#

Create the client once at import or startup, then check flags per request. It is thread-safe, so it works under threaded and async servers.

Flask
from flask import Flask, abort, g
from flags import flags

app = Flask(__name__)

@app.get("/checkout")
def checkout():
    if not flags.is_enabled("new-checkout", {"identifier": g.user_id}):
        abort(404)
    return "new checkout"

Check variants and values#

A flag can serve a named variant, such as a button colour or a plan limit. get_variant gives its key and get_value gives what it carries, or the boolean for a plain flag.

python
variant = flags.get_variant("checkout-layout", user)       # "compact", "wide" or None
limit = flags.get_value("seat-limit", user, fallback=5)    # the variant's value, or 5

everything = flags.evaluate_all(user)                      # a result per flag

Describe the person#

Percentage rollouts bucket on the first identifier. Accounts and devices help targeting rules, and attributes such as plan feed rule conditions. Attributes stay on your server and are never sent to FlagSwift for evaluation. To use one default person for every call, pass global_identifier (a version 1 option) to the constructor.

Real-time updates#

By default the client polls. With streaming on, a flag change reaches your process within moments. The stream carries only a note that something changed, never flag data, and the key travels in a header.

python
flags = FlagSwift(api_key=key, base_url=url, streaming=True, streaming_poll_interval=300.0)
flags.initialize()
flags.get_status()["streaming"]  # "off" | "connecting" | "connected" | "unavailable"

While connected, polling slows to streaming_poll_interval (default 300 seconds) as a safety net. If streaming is off on the server or cannot be kept, polling carries on alone, and evaluation never waits on the stream.

Offline and errors#

Once a configuration has loaded, from the server, a snapshot or a bootstrap, evaluation is purely local. It keeps working with no internet and through a FlagSwift outage, and it never raises.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration stays. The failure shows in get_status() and goes to on_error, and polling backs off up to five minutes. The next success resets it.
First load, nothing storedYou get your fallbacks, then False, until the response arrives. initialize() waits at most init_timeout and does not raise.
Restart during an outageWith snapshot_path the saved file is served from construction. It is written atomically (mode 0600) after every update. A corrupt file, or one from another hashVersion, is ignored.
Bootstrap from your own storageSave flags.get_snapshot() and pass it as bootstrap. It wins over the snapshot file.
Server on an unknown hashVersionThe payload is refused rather than silently putting people in the wrong bucket.
Reading the stateget_status() has last_error, error_count, consecutive_failures, flag_count and last_fetch_time.

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or set auto_exposures=True, and only the person's identifier, the flag, the variant and the event name leave your process.

python
flags.track_exposure("checkout-flow", "u_1")   # evaluates locally, queues the outcome this person got
flags.track("purchase", "u_1", 49.90)          # what they did; the value is optional
flags.flush_analytics()                        # send what is queued now and wait (timeout=10 s)

See Outcomes for how results are read in the console.

Reference#

Package flagswift, Python 3.8 or newer, standard library only, typed (py.typed). Import with from flagswift import FlagSwift. The client is thread-safe and polls on a daemon thread.

Python constructor arguments
ArgumentTypeDescription
api_key, base_url*strRaise FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL when wrong.
environmentstrDefault: the FLAGSWIFT_ENVIRONMENT variable.
refresh_intervalfloatSeconds. Default 30. Zero or falsy turns polling off.
streaming, streaming_poll_intervalbool, floatOpen the real-time stream (see Real-time updates). Default False. While connected, polling slows to streaming_poll_interval seconds, default 300.
timeout, init_timeoutfloatSeconds. Default 5 each. An init_timeout of zero or less means initialize does not wait.
max_retriesintDefault 3.
fallbacksdictFlag key to value.
bootstrapdictA payload. If omitted and snapshot_path is set, the snapshot file is read.
snapshot_pathstrJSON, written atomically (mode 0600). Ignored if it does not have the configuration shape or hashVersion 1.
report_errorsboolDefault True.
on_error, on_updatecallableExceptions raised inside them are swallowed.
failsafe_fallbacks, kill_switch_fallbacks, global_identifierdict, dict, str | listVersion 1 compatibility. failsafe_fallbacks merges under fallbacks; global_identifier is used when no user is passed.
transport, sleep, rndcallableInjectable for tests.
Python methods
MethodDescription
initialize()Starts the polling thread and waits up to init_timeout. Never raises. Also available as a context manager: with FlagSwift(...) as flags.
close() / destroy()Signals the thread to stop. It does not wait for it.
refresh()Fetches now. Never raises; failures go to get_status() and on_error.
evaluate(flag_key, user=None) -> dictenabled, reason and found, plus variant and value for multivariate flags. Never raises.
is_enabled(flag_name, user=None, fallback=None, *, user_id=None) -> booluser_id is a version 1 alias. Honours the local kill switch.
get_variant(flag_key, user=None)The variant key or None.
get_value(flag_key, user=None, fallback=None)Variant value or boolean. Unknown flag: fallback, else the configured one.
evaluate_all(user=None) -> dictA result per flag.
get_all_flags(user=None) -> dictVersion 1: booleans only. Empty while the kill switch is on.
get_flag_keys() / get_snapshot()Known keys and the raw payload.
activate_kill_switch() / deactivate_kill_switch() / is_kill_switch_enabled()Local to this process, no server call, arguments ignored. Only is_enabled and get_all_flags honour it.
track_exposure(flag, user)Evaluates locally and queues the outcome this person got. Never raises.
track(event, user, value=None)Records an outcome after the person's pending exposures.
flush_analytics(timeout=10)Sends what is queued now and waits. auto_exposures=True queues an exposure on every single-flag read (default False).
get_status() -> dictinitialized, environment, version, flag_count, last_fetch_time, last_error, error_count, consecutive_failures, streaming (off, connecting, connected or unavailable) and kill_switch_active, and analytics (pending, sent, dropped, enabled).
FlagSwift.from_config(mapping)Builds a client from a dict of the same arguments.
Python package exports
ExportDescription
check_flag(flag_name, api_key, base_url, environment=None, user=None, **kwargs) -> boolA one-off check that builds, queries and closes a client. Convenient in scripts; slow in a loop.
FlagSwiftError, AuthenticationError, NetworkErrorAuthenticationError is raised for 401 and 403, NetworkError for network errors and timeouts. Errors carry code, status and retryable.
to_context, evaluate, bucket, is_in_rolloutThe engine functions. to_context accepts a string, a list, or a dict with identifier(s), account(s), device(s) and attributes.
FlagSwiftConfig, HASH_VERSION, RULES_VERSION, SDKFlagSwiftConfig is the version 1 name for a plain dict.