references/posthog-python.md · 48000
lues the code branched on. Prefer this over repeated get_feature_flag() calls and over capture(send_feature_flags=True) — it consolidates flag evaluation into a single /flags request per incoming request.
Parameters
distinct_id(Number) - The user's distinct ID. IfNone, falls back to the context distinct_id. If still unresolvable, returns an empty snapshot.groups?(Mapping[str, Union[str, int]]) - Mapping of group type to group key.person_properties?(dict[str, Any]) - Person properties to use for evaluation.group_properties?(dict[str, dict[str, Any]]) - Group properties keyed by group type.only_evaluate_locally(bool) - IfTrue, never fall back to remote evaluation and omit flags that cannot be evaluated locally.disable_geoip?(bool) - Whether to disable GeoIP lookup.flag_keys?(list[str]) - Optional list that scopes local evaluation, the underlying/flagsrequest, and the returned snapshot. When omitted orNone, all flags are evaluated. An empty list returns an empty snapshot without evaluating flags. A requested key absent from loaded local definitions is included in one remote fallback perevaluate_flagscall unlessonly_evaluate_locallyisTrue. If the server also does not know the key, it is omitted from the snapshot.device_id?(str) - Optional device ID override. If not provided, falls back to the context device_id (which may be set via tracing headers). Used by experience-continuity flags to match users across distinct_id changes.
Returns
FeatureFlagEvaluations
Examples
from posthog import evaluate_flags, capture
flags = evaluate_flags("user_123", person_properties={"plan": "enterprise"})
if flags.is_enabled("new-dashboard"):
render_new_dashboard()
capture("page_viewed", distinct_id="user_123", flags=flags)
feature_enabled()
Release Tag: public
Use feature flags to enable or disable features for users.
Notes:
You can call posthog.load_feature_flags() before to make sure you're not doing unexpected requests.
Parameters
key?(str) - The feature flag keydistinct_id?(Number) - The user's distinct IDgroups?(Mapping[str, Union[str, int]]) - Groups mappingperson_properties?(dict[str, Any]) - Person propertiesgroup_properties?(dict[str, dict[str, Any]]) - Group propertiesonly_evaluate_locally(bool) - Whether to evaluate only locallysend_feature_flag_events(bool) - Whether to send feature flag eventsdisable_geoip?(bool) - Whether to disable GeoIP lookupdevice_id?(str) - Optional device ID override for experience-continuity flags
Returns
Optional[bool]
Examples
# Boolean feature flag
from posthog import feature_enabled, get_feature_flag_payload
is_my_flag_enabled = feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
feature_flag_definitions()
Release Tag: public
Returns loaded feature flags.
Notes:
Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.
Returns
None
Examples
from posthog import feature_flag_definitions
definitions = feature_flag_definitions()
get_all_flags()
Release Tag: public
Get all flags for a given user.
Notes:
Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.
Parameters
distinct_id?(Number) - The user's distinct IDgroups?(Mapping[str, Union[str, int]]) - Groups mappingperson_properties?(dict[str, Any]) - Person propertiesgroup_properties?(dict[str, dict[str, Any]]) - Group propertiesonly_evaluate_locally(bool) - Whether to evaluate only locallydisable_geoip?(bool) - Whether to disable GeoIP lookupdevice_id?(str) - Optional device ID override for experience-continuity flagsflag_keys_to_evaluate?(list[str]) - Optional list of flag keys to evaluate (evaluates all if None)
Returns
Optional[dict[str, Union[bool, str]]]
Examples
# All flags for user
from posthog import get_all_flags
get_all_flags('distinct_id_of_your_user')
get_all_flags_and_payloads()
Release Tag: public
Get all feature flag values and payloads for a user.
Parameters
distinct_id?(Number) - The user's distinct ID.groups?(Mapping[str, Union[str, int]]) - Mapping of group type to group key.person_properties?(dict[str, Any]) - Person properties to use for evaluation.group_properties?(dict[str, dict[str, Any]]) - Group properties keyed by group type.only_evaluate_locally(bool) - Whether to evaluate only locally.disable_geoip?(bool) - Whether to disable GeoIP lookup.device_id?(str) - Optional device ID override for experience-continuity flags.flag_keys_to_evaluate?(list[str]) - Optional list of flag keys to evaluate. Evaluates all flags when omitted.
Returns
FlagsAndPayloads
get_feature_flag()
Release Tag: public
Get feature flag variant for users. Used with experiments.
Notes:
groups are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. group_properties take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}.
Parameters
key?(str) - The feature flag keydistinct_id?(Number) - The user's distinct IDgroups?(Mapping[str, Union[str, int]]) - Groups mapping from group type to group keyperson_properties?(dict[str, Any]) - Person propertiesgroup_properties?(dict[str, dict[str, Any]]) - Group properties in format { group_type_name: { group_properties } }only_evaluate_locally(bool) - Whether to evaluate only locallysend_feature_flag_events(bool) - Whether to send feature flag eventsdisable_geoip?(bool) - Whether to disable GeoIP lookupdevice_id?(str) - Optional device ID override for experience-continuity flags
Returns
Union[bool, str, any]
Examples
# Multivariate feature flag
from posthog import get_feature_flag, get_feature_flag_payload
enabled_variant = get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key':
matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
get_feature_flag_evaluation_runtime()
Release Tag: public
Return where a locally loaded feature flag is meant to be evaluated.
Notes:
Reads the evaluation_runtime each flag definition carries, so no extra request is made. Returns None when local evaluation has not loaded a definition for this key. A definition that carries no runtime reports FeatureFlagEvaluationRuntime.ALL, the default PostHog applies.
Parameters
key?(str)
Returns
Optional[FeatureFlagEvaluationRuntime]
Examples
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_evaluation_runtime
runtime = get_feature_flag_evaluation_runtime("my-flag")
get_feature_flag_keys_by_evaluation_runtime()
Release Tag: public
Return the keys of locally loaded flags that a runtime can evaluate.
Notes:
A flag set to FeatureFlagEvaluationRuntime.ALL suits either runtime, so it is returned for CLIENT and for SERVER. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.
Parameters
evaluation_runtime?(FeatureFlagEvaluationRuntime)
Returns
list[str]
Examples
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_keys_by_evaluation_runtime
client_keys = get_feature_flag_keys_by_evaluation_runtime(FeatureFlagEvaluationRuntime.CLIENT)
get_feature_flag_payload()
Release Tag: public
Get the payload associated with a feature flag value. Deprecated for new code. Prefer evaluate_flags() and flags.get_flag_payload(key) so flag evaluation happens once per request.
Parameters
key?(str) - The feature flag key.distinct_id?(Number) - The user's distinct ID.match_value(bool) - Optional flag value to use when selecting a payload.groups?(Mapping[str, Union[str, int]]) - Mapping of group type to group key.person_properties?(dict[str, Any]) - Person properties to use for evaluation.group_properties?(dict[str, dict[str, Any]]) - Group properties keyed by group type.only_evaluate_locally(bool) - Whether to evaluate only locally.send_feature_flag_events(bool) - Whether to send a $feature_flag_called event.disable_geoip?(bool) - Whether to disable GeoIP lookup.device_id?(str) - Optional device ID override for experience-continuity flags.
Returns
Optional[object]
load_feature_flags()
Release Tag: public
Load feature flag definitions from PostHog.
Returns
None
Examples
from posthog import load_feature_flags
load_feature_flags()
Client management methods
flush()
Release Tag: public
Attempt immediate delivery of queued events and ended spans, keeping the global client reusable. Call flush() before a short-lived request or serverless invocation returns when using the shared module-level client. Use shutdown() only for final process cleanup or a client that will not be reused. Flush does not stop the background workers or feature flag poller, and does not end open spans. Returning does not guarantee server receipt: pending work can remain after a timeout or span export failure, and failed events may be dropped by consumers. Calls made directly from SDK callbacks such as on_error are deferred rather than blocking the worker that invoked the callback.
Parameters
timeout_seconds?(float) - Seconds to wait for event queues to drain, shared across event lanes. Defaults to 10 seconds. PassNoneto wait without a time limit; this does not guarantee successful delivery. Queued spans flush concurrently, waiting up to this many seconds for an in-flight flush before starting a fresh drain budget. A lock wait timeout leaves the in-flight flush to finish. At least one span request is attempted after acquiring the lock, even with no budget left; retriable failures are retried after backoff while budget remains, with one last attempt at the deadline. The last span request is not cut short and is bounded by the client'stimeoutin seconds, so this is not a strict wall-clock limit for the whole call. WithNone, a retriable span failure is left for a later flush rather than retried within this call.
Returns
any
Examples
import posthog
posthog.capture('event_name', distinct_id='user_id')
# Before a serverless invocation returns; keep the global client open.
posthog.flush(timeout_seconds=10)
join()
Release Tag: public
Attempt to process queued events and stop the client's background workers. Use shutdown() directly in most cases. Failed or undrainable events may be dropped and reported through logging or on_error; returning does not guarantee server receipt. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry.
Returns
any
Examples
from posthog import join
join()
shutdown()
Release Tag: public
Attempt final delivery and permanently shut down the global client. Call this for final process cleanup, not at the end of each request or serverless invocation that shares the module-level client. Use flush() before returning from those invocations instead. Shutdown closes capture lanes, stops background workers and the feature flag poller, and tears down integrations. The global client is not recreated automatically after shutdown. This normally blocks until queued events have been attempted and cleanup finishes. Failed or undrainable events may be dropped and reported through logging or on_error; returning does not guarantee server receipt. Event draining has no timeout. Queued spans get a final flush with up to 30 seconds waiting for an in-flight flush, then a fresh 30-second drain budget; the last HTTP request is not cut short. Unsent queued spans and still-open spans are discarded with a warning. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. Calls made directly from SDK callbacks such as on_error are deferred to avoid deadlocking the worker. If blocking completion is required, signal an application-owned thread, return from the callback, and call shutdown() from that thread. Do not wait inside a callback for another thread or task calling a lifecycle method.
Returns
any
Examples
from posthog import shutdown
shutdown()
Tracing methods
get_active_span()
Release Tag: public
The span that is active in the current context, or None. Alpha. Only entering a span (with posthog.start_span(...) as span:) makes it active; a span started manually is not. Use it to propagate the trace to the next service: span.traceparent() is the header value.
Returns
Optional[Span]
Examples
span = posthog.get_active_span()
if span is not None:
headers["traceparent"] = span.traceparent()
start_span()
Release Tag: public
Start a span for distributed tracing. Alpha. Returns a span handle. Use it as a context manager to make it the active span for the block and end it on exit (recording a raised exception on the way out); or call end() yourself for a span that cannot wrap a block. Spans started inside the block nest under it automatically. Always returns a usable handle, even when tracing is off, so calling code never branches.
Parameters
name?(str) - A low-cardinality operation name, e.g.GET /users/:id. Variable values belong in attributes, not the name.kind?(str) -internal(default),server,client,producerorconsumer.attributes?(Mapping[str, Any]) - Initial attributes.parent(Span) - A span handle, or an inbound W3Ctraceparentheader value to continue a remote trace. Defaults to the active span.tracestate?(str) - The inboundtracestateheader accompanying atraceparentstringparent; preserved and propagated.start_time(datetime) - Adatetimeor epoch seconds, to backdate the span.
Returns
Span
Examples
import posthog
posthog.traces = {"service_name": "checkout-api"}
with posthog.start_span("POST /checkout", parent=request.headers.get("traceparent")) as span:
span.set_attribute("plan", user.plan)
with posthog.start_span("db.query", kind="client"):
...
outgoing_headers = {"traceparent": span.traceparent()}
Other methods
get_feature_flag_result()
Release Tag: public
Get a FeatureFlagResult object which contains the flag result and payload. This method evaluates a feature flag and returns a FeatureFlagResult object containing: - enabled: Whether the flag is enabled - variant: The variant value if the flag has variants - payload: The payload associated with the flag (automatically deserialized from JSON) - key: The flag key - reason: Why the flag was enabled/disabled
Parameters
key?(str) - The feature flag key.distinct_id?(Number) - The user's distinct ID.groups?(Mapping[str, Union[str, int]]) - Mapping of group type to group key.person_properties?(dict[str, Any]) - Person properties to use for evaluation.group_properties?(dict[str, dict[str, Any]]) - Group properties keyed by group type.only_evaluate_locally(bool) - Whether to evaluate only locally.send_feature_flag_events(bool) - Whether to send a $feature_flag_called event.disable_geoip?(bool) - Whether to disable GeoIP lookup.device_id?(str) - Optional device ID override for experience-continuity flags.
Returns
Optional[FeatureFlagResult]
get_remote_config_payload()
Release Tag: public
Get the payload for a remote config feature flag.
Parameters
key?(str) - The key of the feature flag
Returns
None
set_code_variables_mask_url_credentials_context()
Release Tag: public
Whether to scrub credentials embedded in URLs/DSNs (e.g. user:pass@host) from captured code variables for the current context.
Parameters
enabled?(bool)
Returns
None
Contexts methods
get_tags()
Release Tag: public
Get all tags from the current context. Returns: Dict of all tags in the current context
Returns
dict[str, Any]
new_context()
Release Tag: public
Create a new context scope that will be active for the duration of the with block.
Parameters
fresh(bool) - Whether to start with a fresh context (default: False)capture_exceptions?(bool) - Whether to capture exceptions raised within the context. If omitted, defaults to the relevant client's exception autocapture setting.client?(Client) - Optional Posthog client instance to use for this context (default: None)
Returns
None
Examples
from posthog import new_context, tag, capture
with new_context():
tag("request_id", "123")
capture("event_name", properties={"property": "value"})
scoped()
Release Tag: public
Decorator that creates a new context for the function.
Parameters
fresh(bool) - Whether to start with a fresh context (default: False)capture_exceptions?(bool) - Whether to capture and track exceptions with posthog error tracking. If omitted, defaults to the global exception autocapture setting.
Returns
None
Examples
from posthog import scoped, tag, capture
@scoped()
def process_payment(payment_id):
tag("payment_id", payment_id)
capture("payment_started")
set_capture_exception_code_variables_context()
Release Tag: public
Override code-variable capture for exceptions in the current context.
Parameters
enabled?(bool) - Whether exceptions captured in this context should include local variable values from stack frames.
Returns
None
set_code_variables_detect_secrets_context()
Release Tag: public
Whether to apply entropy-based secret detection as a last-resort redaction of high-entropy values (API keys, tokens, strong passwords) in captured code variables for the current context.
Parameters
enabled?(bool)
Returns
None
set_code_variables_ignore_patterns_context()
Release Tag: public
Override code-variable ignore patterns for exceptions in the current context.
Parameters
ignore_patterns?(list[str]) - Variable-name patterns that should be omitted entirely when code variables are captured.
Returns
None
set_code_variables_mask_patterns_context()
Release Tag: public
Override code-variable mask patterns for exceptions in the current context.
Parameters
mask_patterns?(list[str]) - Variable-name patterns whose values should be replaced with***when code variables are captured.
Returns
None
set_context_device_id()
Release Tag: public
Set the device ID for the current context, associating all feature flag requests in this or child contexts with the given device ID.
Parameters
device_id?(str) - The device ID to associate with the current context and its children
Returns
None
Examples
from posthog import set_context_device_id
set_context_device_id("device_123")
set_context_session()
Release Tag: public
Set the session ID for the current context.
Parameters
session_id?(str) - The session ID to associate with the current context and its children
Returns
None
Examples
from posthog import set_context_session
set_context_session("session_123")
tag()
Release Tag: public
Add a tag to the current context.
Parameters
name?(str) - The tag keyvalue?(Any) - The tag value
Returns
None
Examples
from posthog import tag
tag("user_id", "123")
Initialization methods
setup()
Release Tag: public
Create or return the global PostHog client configured by module settings. Most applications should either instantiate Posthog directly or set posthog.api_key/other module settings before calling top-level helpers. setup() is called automatically by global APIs such as capture(). Returns: The global Client instance. If both api_key and project_api_key are missing or blank, the client is disabled and module-level calls become no-ops.
Returns
Client