Feature flags in Python: build one without a vendor SDK
A feature flag in Python does not require a vendor SDK. You need a place to store the flag, a deterministic function that assigns each user to a variant, and a check at the call site. That is the whole mechanism; a vendor SDK mostly wraps it in a network call and a dashboard.
Most Python teams reach for a package like LaunchDarkly’s launchdarkly-server-sdk, or they hand-roll a dictionary of booleans in a settings file. Both work. The dashboard version disconnects the flag from the code review that gates it. The dictionary version has no audit trail: nobody can tell who added a flag or why it is still there.
This guide builds a feature flag in Python from the standard library. The definition lives in a file your team reviews in a pull request, and the hashing math gets checked against a real fixture instead of trusted by inspection.
Key Takeaways
- A feature flag in Python needs three things: a stored definition, a deterministic assignment function, and a check at the call site. No vendor SDK required.
- The hashing approach dif uses, the first 4 bytes of
SHA-256(salt + user_id)read as an integer, modulo 10,000, runs in about 10 lines of Python with only the standard library.- Storing each flag as a file with frontmatter (
owner,variants,weights) gets the same pull-request review and git history dif’s format gives JavaScript and TypeScript codebases.- dif does not ship an official Python SDK yet. Write the assignment function yourself, and test it against known values instead of trusting it by inspection.
- Because the bucketing math is only hashing and modulo, you can verify a Python port against a shared test fixture rather than guessing it is correct.
What a feature flag in Python actually needs
Strip away the dashboard, and a feature flag is three parts: a definition (who owns it, what the variants are, and their weights), a deterministic function that turns a user id into one of those variants, and a check at the call site that branches on the result.
A growth PM reads the definition and knows who to ask about a flag without opening a ticket. An engineer reads the function and verifies it is correct by running it twice with the same input and getting the same answer. Neither needs a hosted service for that. The function below is the entire runtime cost, and it runs in microseconds with zero network calls. It is the same model dif’s feature flags page describes for JavaScript and TypeScript teams, ported to Python.
Deterministic bucketing: the hash function behind the flag
dif’s own SDK (JavaScript and TypeScript only, for now) assigns a variant by hashing a salt and the user id, then taking the result modulo the bucket count. The bucket is the first 4 bytes of SHA-256(salt + user_id), read as a big-endian integer, modulo 10,000. The variant is picked from cumulative weights.
Ported to Python with only the standard library:
import hashlib
BUCKET_COUNT = 10_000
def bucket_for(salt: str, user_id: str) -> int:
digest = hashlib.sha256(f"{salt}{user_id}".encode()).digest()
return int.from_bytes(digest[:4], "big") % BUCKET_COUNT
def assign(weights: dict[str, int], salt: str, user_id: str) -> str:
n = bucket_for(salt, user_id)
cumulative = 0
for variant, weight in weights.items():
cumulative += weight
if n < cumulative:
return variant
return next(iter(weights))
Call bucket_for("new-checkout", "u_8131") twice and it returns the same number both times, because nothing is random and nothing is stored. Use the flag’s own id as the salt, so two different flags hash the same user id into unrelated numbers. Being in the 10% for one rollout says nothing about the next.
Store the flag as a file, not a global dict
A dict of booleans in settings.py has no owner and no history beyond git blame. There is no way to review a weight change except reading a diff of 0.1 to 0.5. Model the definition the way dif does: one file per flag, YAML frontmatter on top, checked into git next to the code it gates, the same pattern covered in feature flags in git.
---
id: new-checkout
owner: priya@acme.com
audience: all_users
variants:
control: 5000
on: 5000
metric: completed_checkout
---
Rolling out the rewritten checkout flow. Holding at 50% until conversion
and error rate both clear the guardrail.
Reading it back is a few lines:
import re
import yaml
FRONTMATTER = re.compile(r"^---\n(.*?)\n---\n", re.DOTALL)
def load_flag(path: str) -> dict:
text = open(path, encoding="utf-8").read()
return yaml.safe_load(FRONTMATTER.match(text).group(1))
The weights, the owner, and the reason the flag exists now live in the same file, in the same pull request, with the same git history as the code it gates. The .md format covers the full frontmatter reference if you want to match it field for field.
Verify the Python port against real bucket values
Hashing math is easy to get subtly wrong: a little-endian read instead of big-endian, 2 bytes instead of 4, or a modulo applied before the bytes are joined. Each mistake still runs and still returns a number, so a bug here hides until two services disagree on the same user’s variant.
dif locks Rust and TypeScript to the same math with a shared fixture, bucket_tests.json: pairs of salt, user id, and the bucket they must produce. Because dif is open source, you can pull the same fixture and run the same assertion against a Python port:
import json
import pytest
from flags import bucket_for
with open("bucket_tests.json") as f:
CASES = json.load(f)
@pytest.mark.parametrize("case", CASES)
def test_matches_fixture(case):
assert bucket_for(case["salt"], case["user_id"]) == case["bucket"]
If the Python port drifts from the fixture by even one bucket, this fails before it reaches a user. That is the same guarantee dif validate gives a JavaScript codebase in CI.
Wire the flag into a Flask or FastAPI route
The function does not care which framework calls it. In Flask, resolve the user id once per request and fail to a default if it is missing:
from flask import Flask, request, g
app = Flask(__name__)
FLAGS = {"new-checkout": load_flag("flags/new-checkout.md")}
@app.before_request
def resolve_user():
g.user_id = request.headers.get("X-User-Id")
def dif(flag_id: str) -> str:
flag = FLAGS.get(flag_id)
if not flag or not g.user_id:
return "control"
return assign(flag["variants"], flag_id, g.user_id)
@app.route("/checkout")
def checkout():
if dif("new-checkout") == "on":
return new_checkout()
return legacy_checkout()
A missing flag, a missing user id, or an exception in load_flag all fall through to control, and nothing gets recorded. That is the same fail-safe default dif’s own SDK uses: a flag system should not fail worse than not shipping the feature at all.
What you give up without a vendor SDK
This gets you assignment, nothing else. There is no built-in exposure tracking. If you want to know who saw which variant, write that event yourself and send it to whatever you already use (Segment, Amplitude, a warehouse table). There is also no dashboard for a non-engineer to flip a flag without a pull request. That is the same tradeoff dif makes by design: a change goes through code review, not a toggle.
dif validate’s orphan check scans source for dif("...") call sites written in JavaScript or TypeScript syntax. It will not find the Python call above. The weight and owner checks in the same command still work, because they read the flag file itself, not the application code. For a payment path that needs a sub-second kill switch flipped by someone outside engineering, a vendor SDK like LaunchDarkly’s Python client is the right tool. For everything else, a hash function and a file in the repo covers it.
Getting started
Store the flag the way dif does, even if nothing reads it with dif’s own SDK:
npm install -g @dif.sh/cli
dif init
dif init scaffolds a dif/ directory and the agent files. dif new drafts a flag with the frontmatter fields shown above. dif validate checks the weights and the owner before you ever write a line of Python. Point load_flag at the resulting file, and the assignment function in this guide does the rest.
A feature flag in Python comes down to a hash function, a file, and a check at the call site. The hash function is 10 lines of the standard library. The file gets an owner, a reason, and a pull request instead of a silent edit to a dict. Verifying the port against a real fixture is what makes it trustworthy instead of merely plausible.
FAQ
Is there a feature flag library for Python? Yes. Several vendor SDKs support Python, including LaunchDarkly’s launchdarkly-server-sdk and Split’s Python client. For a hash-based flag with no dashboard, you do not need one: the deterministic assignment function is about 10 lines of the standard library, shown above.
Does dif have a Python SDK? Not yet. The SDK is JavaScript and TypeScript, with React and Svelte adapters. The CLI and the file format are language-agnostic, so you can still store a Python service’s flags as .md files and validate them with dif validate, then write a small assignment function to read them.
What is deterministic bucketing? A way to assign a user to a variant without storing anything. The user id is hashed with a salt, and the result modulo the bucket count picks the variant. The same user id always lands in the same bucket, so there is no assignment database and no flicker across requests.
Should a feature flag fail open or fail closed? Fail to the control or default variant, and record nothing. A missing flag, a missing user id, or an error reading the definition should look like the flag was never there, not crash the request. That keeps the data clean and the worst case no worse than not shipping the feature.
How do I test a feature flag hashing function? Assert it against known salt, user id, and bucket triples instead of trusting the math by inspection. dif locks Rust and TypeScript to the same values with a shared fixture; port the same test to Python, or any language, and the assertion catches a drift of even one bucket.