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#
pip install flagswiftIt 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.
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.
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.
| Argument | Type | Description |
|---|---|---|
| api_key, base_url* | str | A server or admin key and your server address. A mistake raises FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL. |
| environment | str | Only for project-wide keys. Default: the FLAGSWIFT_ENVIRONMENT variable. |
| refresh_interval | float | Seconds between checks for changes. Default 30. Zero turns polling off. |
| streaming | bool | Keep one real-time connection open so changes arrive within moments. Default False. |
| fallbacks | dict | Flag key to value, served for unknown flags and before anything loads. |
| snapshot_path | str | JSON file that keeps the last configuration across restarts. |
| bootstrap | dict | A payload to start from, such as flags.get_snapshot() you saved. |
| timeout, init_timeout | float | Seconds. Default 5 each. |
| max_retries | int | Default 3. |
| auto_exposures | bool | Queue an exposure on every single-flag read. Default False. |
| on_error, on_update | callable | Callbacks. 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.
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.
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.
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.
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 flagDescribe 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.
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.
| Situation | Description |
|---|---|
| A refresh fails | The 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 stored | You get your fallbacks, then False, until the response arrives. initialize() waits at most init_timeout and does not raise. |
| Restart during an outage | With 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 storage | Save flags.get_snapshot() and pass it as bootstrap. It wins over the snapshot file. |
| Server on an unknown hashVersion | The payload is refused rather than silently putting people in the wrong bucket. |
| Reading the state | get_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.
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.
| Argument | Type | Description |
|---|---|---|
| api_key, base_url* | str | Raise FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL when wrong. |
| environment | str | Default: the FLAGSWIFT_ENVIRONMENT variable. |
| refresh_interval | float | Seconds. Default 30. Zero or falsy turns polling off. |
| streaming, streaming_poll_interval | bool, float | Open the real-time stream (see Real-time updates). Default False. While connected, polling slows to streaming_poll_interval seconds, default 300. |
| timeout, init_timeout | float | Seconds. Default 5 each. An init_timeout of zero or less means initialize does not wait. |
| max_retries | int | Default 3. |
| fallbacks | dict | Flag key to value. |
| bootstrap | dict | A payload. If omitted and snapshot_path is set, the snapshot file is read. |
| snapshot_path | str | JSON, written atomically (mode 0600). Ignored if it does not have the configuration shape or hashVersion 1. |
| report_errors | bool | Default True. |
| on_error, on_update | callable | Exceptions raised inside them are swallowed. |
| failsafe_fallbacks, kill_switch_fallbacks, global_identifier | dict, dict, str | list | Version 1 compatibility. failsafe_fallbacks merges under fallbacks; global_identifier is used when no user is passed. |
| transport, sleep, rnd | callable | Injectable for tests. |
| Method | Description |
|---|---|
| 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) -> dict | enabled, reason and found, plus variant and value for multivariate flags. Never raises. |
| is_enabled(flag_name, user=None, fallback=None, *, user_id=None) -> bool | user_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) -> dict | A result per flag. |
| get_all_flags(user=None) -> dict | Version 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() -> dict | initialized, 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. |
| Export | Description |
|---|---|
| check_flag(flag_name, api_key, base_url, environment=None, user=None, **kwargs) -> bool | A one-off check that builds, queries and closes a client. Convenient in scripts; slow in a loop. |
| FlagSwiftError, AuthenticationError, NetworkError | AuthenticationError is raised for 401 and 403, NetworkError for network errors and timeouts. Errors carry code, status and retryable. |
| to_context, evaluate, bucket, is_in_rollout | The 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, SDK | FlagSwiftConfig is the version 1 name for a plain dict. |