references/posthog-python.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
PostHog Python SDK
SDK Version: 7.76.0
Integrate PostHog into any python application.
Categories
- Initialization
- Identification
- Capture
- Error Tracking
- Feature flags
- Tracing
- Contexts
- Events
- Client management
PostHog
This is the SDK reference for the PostHog Python SDK. You can learn more about example usage in the Python SDK documentation. You can also follow Flask and Django guides to integrate PostHog into your project. For long-running applications, create one client during application startup and reuse it for the lifetime of the process. This keeps background queues predictable and makes shutdown flushing straightforward. Multiple clients are still supported for intentional multi-project or multi-host setups.
Initialization methods
Client()
Release Tag: public
Initialize a new PostHog client instance.
Parameters
project_api_key?(str) - PostHog project API key/token.host(any) - PostHog host. Defaults to the US ingestion endpoint when not set. App hosts such ashttps://us.posthog.comare mapped to the corresponding ingestion host.debug(bool) - Enable verbose SDK logging and re-raise errors from public API methods.max_queue_size(int) - Maximum number of events buffered before upload.send(bool) - If False, queueing succeeds but events are not sent.on_error(any) - Optional callback invoked by background consumers when an upload fails. Keep it short and non-blocking. Calling lifecycle methods directly is safe and deferred, but do not start another thread or task that callsflush(),join(), orshutdown()and then wait for it from the callback.flush_at(int) - Number of queued events that triggers a batch upload.flush_interval(float) - Maximum seconds a background consumer waits before flushing a partial batch.gzip(bool) - Whether to gzip event upload payloads.max_retries(int) - Number of upload retries. Values below 0 are treated as 0.sync_mode(bool) - If True, send each event synchronously instead of using background worker threads. This blocks the calling thread; in asyncio applications such as FastAPI, useAsyncPosthoginstead.timeout(float) - HTTP request timeout in seconds for event uploads.thread(int) - Number of background consumer threads.poll_interval(int) - Seconds between local feature flag definition refreshes.personal_api_key(any) - Deprecated alias forsecret_key. Still honored for backwards compatibility; prefersecret_key, which also accepts a Project Secret API Key.disabled(bool) - If True, disable captures and API requests. Useful in tests.disable_geoip(bool) - Whether to disable server-side GeoIP enrichment. Defaults to True.is_server(bool) - Whether events are emitted from a server-side runtime. Defaults to True; set to False when using the SDK as a client/CLI so the device OS is attributed to the person normally.historical_migration(bool) - Mark events as historical migration imports.feature_flags_request_timeout_seconds(float) - Timeout in seconds for feature flag and remote config requests.feature_flags_request_max_retries(int) - Number of retries for feature flag requests after network, transport, or timeout failures. Defaults to 1. Set to 0 to disable retries.super_properties(any) - Properties merged into every captured event.enable_exception_autocapture(bool) - Automatically capture uncaught exceptions.log_captured_exceptions(bool) - Also log exceptions captured by error tracking.project_root(any) - Root path used to determine in-app stack frames for captured exceptions. Defaults to the current working directory.privacy_mode(bool) - For AI observability, capture usage metadata without prompt inputs or outputs.before_send(any) - Optional callback that can modify or drop events before upload. ReturnNoneto drop an event.flag_fallback_cache_url(any) - Optional feature flag fallback cache URL, such asmemory://local/?ttl=300&size=10000or a Redis URL.enable_local_evaluation(bool) - Whether to poll feature flag definitions for local evaluation when a personal API key is configured.flag_definition_cache_provider?(FlagDefinitionCacheProvider) - Optional external cache provider for sharing feature flag definitions across workers.capture_exception_code_variables(bool) - Capture local variable values on exception stack frames.code_variables_mask_patterns(any) - Variable-name patterns to mask when capturing code variables.code_variables_ignore_patterns(any) - Variable-name patterns to omit when capturing code variables.code_variables_mask_url_credentials(any) - Scrub credentials embedded in URLs/DSNs (e.g.user:pass@host) from captured code variables, regardless of the surrounding variable name. Defaults to True.code_variables_detect_secrets(any) - Last-resort entropy-based detection that redacts high-entropy secret-looking values (API keys, tokens, strong passwords) sitting in innocuously-named variables, after the name and URL checks. Skips structured ids (UUIDs, ObjectIds, hashes). Defaults to True.in_app_modules(UnionType[list[str], any]) - Module/package prefixes treated as in-app frames in captured exceptions.enable_exception_autocapture_rate_limiting(bool) - Rate limit autocaptured exceptions client-side with a token bucket per exception type. Disabled by default.exception_autocapture_bucket_size(int) - Maximum burst of autocaptured exceptions allowed per exception type (token bucket size, clamped to 0-100).exception_autocapture_refill_rate(int) - Tokens restored per refill interval for each exception type's bucket.exception_autocapture_refill_interval_seconds(int) - Seconds between token refills for autocaptured exception rate limiting.capture_mode(CaptureMode) - Capture wire protocol to use. Defaults toCaptureMode.V0(legacy/batch/). SetCaptureMode.V1(or pass the string"v1") to opt into/i/v1/analytics/events. When omitted, thePOSTHOG_CAPTURE_MODEenv var is consulted, thenV0.capture_compression(CaptureCompression) - Request-body compression for capture-v1 uploads (ignored in V0, which usesgzip).CaptureCompression.GZIPorDEFLATE(or the strings"gzip"/"deflate"). When omitted, thePOSTHOG_CAPTURE_COMPRESSIONenv var is consulted, then the legacygzipflag, then no compression.secret_key(any) - A Personal API Key or Project Secret API Key, used to authenticate local feature flag evaluation, remote config payloads, and decrypted flag payloads. Example:: posthog.Client(project_api_key, secret_key="phx_...")metrics?(dict)enable_full_ai_capture(bool) - Route PostHog AI wrapper events through the dedicated AI capture endpoint and capture full AI content: skips string truncation and passes media (base64/data URIs) through unredacted.privacy_modealways wins. Defaults to False.capture_trace_context(bool) - When OpenTelemetry is installed and a valid span is active at capture time, add its trace and span IDs as$trace_idand$span_idproperties to events captured withcapture()andcapture_ai(), so they can be correlated with backend traces. Explicit$trace_id/$span_idvalues passed inpropertieswin. Exception events (capture_exception) always attach these IDs regardless of this setting. Defaults to False._use_ai_lane(bool)_enable_multimodal_capture(bool)traces?(dict) - Config dict for distributed tracing:service_name,service_version,environment,resource_attributes,flush_interval(5 s),max_queue_size(2048),max_export_batch_size(512),max_live_spans(10000),max_span_age(3600 s),max_attributes_per_span(128),max_events_per_span(128),max_attribute_value_length(8192).before_span_sendis a callable, or a list run in order, that receives each finished span as a dict (trace_id,span_idandparent_span_idare read-only) and returns it, edited, orNoneto drop it; a hook that raises drops the span. Tracing is off until this is provided. Spans export on a background timer even withsync_mode; serverless handlers should callflush()before returning. Defaults to None.
Returns
None
Examples
from posthog import Posthog
posthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')
Identification methods
alias()
Release Tag: public
Create an alias between two distinct IDs.
Parameters
previous_id?(Number) - The previous distinct ID. Required - the call is dropped with a warning if it is missing or empty.distinct_id?(str) - The new distinct ID to alias to. Falls back to the context distinct ID; the call is dropped with a warning if neither is available.timestamp(datetime) - The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.uuid?(str) - A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID.disable_geoip?(bool) - Whether to disable GeoIP for this event.
Returns
Optional[str]
Examples
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')
group_identify()
Release Tag: public
Identify a group and set its properties.
Parameters
group_type?(str) - The type of group (e.g., 'company', 'team'). Required - the call is dropped with a warning if it is missing or empty.group_key?(str) - The unique identifier for the group. Required - the call is dropped with a warning if it is missing or empty.properties?(dict[str, Any]) - A dictionary of properties to set on the group.timestamp(datetime) - The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.uuid(str) - A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID.disable_geoip?(bool) - Whether to disable GeoIP for this event.distinct_id(Number) - The distinct ID of the user performing the action.
Returns
Optional[str]
Examples
posthog.group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})
set()
Release Tag: public
Set properties on a person profile.
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
# Set with distinct id
posthog.set(distinct_id='user123', properties={'name': 'Max Hedgehog'})
set_once()
Release Tag: public
Set properties on a person profile only if they haven't been set before.
Parameters
kwargs?(Unpack[OptionalSetArgs])
Returns
Optional[str]
Examples
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})
Capture methods
capture()
Release Tag: public
Captures an event manually. Learn about capture best practices
Parameters
event?(str) - The event name to capture.kwargs?(Unpack[OptionalCaptureArgs])
Returns
Optional[str]
Examples
Anonymous event
# Anonymous event
posthog.capture('some-anon-event')
Context usage
# Context usage
from posthog import identify_context, new_context
with new_context():
identify_context('distinct_id_of_the_user')
posthog.capture('user_signed_up')
posthog.capture('user_logged_in')
posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')
Set event properties
# Set event properties
posthog.capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)
Page view event
# Page view event
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})
capture_ai()
Release Tag: public
Capture an AI event on the dedicated AI capture endpoint. Beta: the signature is stable; operational limits (per-event size cap, batching, endpoint) may change without notice. Takes the same arguments and returns the same value as capture(): the event UUID, or None when the event was not admitted (disabled client, or dropped by before_send). The event is queued on an isolated AI lane with its own consumer pool and a higher per-event size cap, posting to the dedicated AI ingestion endpoint. The payload is sent as given — no redaction or truncation is applied here.
Parameters
event?(str)kwargs?(Unpack[OptionalCaptureArgs])
Returns
Optional[str]
Error Tracking methods
capture_exception()
Release Tag: public
Capture an exception for error tracking. When OpenTelemetry is installed and a valid span is active, its trace and span IDs are added as $trace_id and $span_id event properties.
Parameters
exception?(BaseException) - The exception to capture.kwargs?(Unpack[OptionalCaptureArgs])
Returns
Optional[str]
Examples
try:
# Some code that might fail
pass
except Exception as e:
posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)
Feature flags methods
evaluate_flags()
Release Tag: public
Evaluate all feature flags for a user in a single call and return a :class:FeatureFlagEvaluations snapshot. Branch on .is_enabled() / .get_flag() and pass the same snapshot to :meth:capture via the flags option so events carry the exact flag values 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. Local evaluation is transparent: when the poller resolves a flag, the snapshot's $feature_flag_called events are tagged locally_evaluated=True and reason "Evaluated locally".
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) - If True, never fall back to remote evaluation — flags that can't be evaluated locally are simply omitted from the snapshot.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_locallyis True. 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
flags = posthog.evaluate_flags(
"user_123",
person_properties={"plan": "enterprise"},
)
if flags.is_enabled("new-dashboard"):
render_new_dashboard()
posthog.capture("page_viewed", distinct_id="user_123", flags=flags)
feature_enabled()
Release Tag: public
Check if a feature flag is enabled for a user.
Parameters
key?(str) - The feature flag key.distinct_id?(Number) - The distinct ID of the user.groups?(Mapping[str, Union[str, int]]) - A dictionary of group information.person_properties?(dict[str, Any]) - A dictionary of person properties.group_properties?(dict[str, dict[str, Any]]) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip?(bool) - Whether to disable GeoIP for this request.device_id?(str) - The device ID for this request.
Returns
Optional[bool]
Examples
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
feature_flag_definitions()
Release Tag: public
Return feature flag definitions loaded for local evaluation. Returns: The currently loaded feature flag definitions, or None before local evaluation has loaded definitions.
Returns
None
get_all_flags()
Release Tag: public
Get all feature flags for a user.
Parameters
distinct_id?(Number) - The distinct ID of the user.groups?(Mapping[str, Union[str, int]]) - A dictionary of group information.person_properties?(dict[str, Any]) - A dictionary of person properties.group_properties?(dict[str, dict[str, Any]]) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.disable_geoip?(bool) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.device_id?(str) - The device ID for this request.
Returns
Optional[dict[str, Union[bool, str]]]
Examples
posthog.get_all_flags('distinct_id_of_your_user')
get_all_flags_and_payloads()
Release Tag: public
Get all feature flags and their payloads for a user.
Parameters
distinct_id?(Number) - The distinct ID of the user.groups?(Mapping[str, Union[str, int]]) - A dictionary of group information.person_properties?(dict[str, Any]) - A dictionary of person properties.group_properties?(dict[str, dict[str, Any]]) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.disable_geoip?(bool) - Whether to disable GeoIP for this request.flag_keys_to_evaluate?(list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.device_id?(str) - The device ID for this request.
Returns
FlagsAndPayloads
Examples
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')
get_feature_flag()
Release Tag: public
Get multivariate feature flag value for a user.
Parameters
key?(str) - The feature flag key.distinct_id?(Number) - The distinct ID of the user.groups?(Mapping[str, Union[str, int]]) - A dictionary of group information.person_properties?(dict[str, Any]) - A dictionary of person properties.group_properties?(dict[str, dict[str, Any]]) - A dictionary of group properties.only_evaluate_locally(bool) - Whether to only evaluate locally.send_feature_flag_events(bool) - Whether to send feature flag events.disable_geoip?(bool) - Whether to disable GeoIP for this request.device_id?(str) - The device ID for this request.
Returns
Union[bool, str, any]
Examples
enabled_variant = posthog.get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key': # replace 'variant-key' with the key of your variant
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = posthog.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.
Parameters
key?(str) - The feature flag key.
Returns
Optional[FeatureFlagEvaluationRuntime]
Examples
from posthog import FeatureFlagEvaluationRuntime
runtime = posthog.get_feature_flag_evaluation_runtime("my-flag")
if runtime is FeatureFlagEvaluationRuntime.SERVER:
...
get_feature_flag_keys_by_evaluation_runtime()
Release Tag: public
Return the keys of locally loaded flags that a runtime can evaluate. A flag set to FeatureFlagEvaluationRuntime.ALL suits either runtime, so it is returned for CLIENT and for SERVER, and asking for ALL returns every loaded flag. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.
Parameters
evaluation_runtime?(FeatureFlagEvaluationRuntime) - The runtime to match, as aFeatureFlagEvaluationRuntimeor its string value.
Returns
list[str]
Examples
from posthog import FeatureFlagEvaluationRuntime
client_keys = posthog.get_feature_flag_keys_by_evaluation_runtime(
FeatureFlagEvaluationRuntime.CLIENT
)
get_feature_flag_payload()
Release Tag: public
Get the payload for a feature flag.
Parameters
key?(str) - The feature flag key.distinct_id?(Number) - The distinct ID of the user.match_value(bool) - The specific flag value to get payload for.groups?(Mapping[str, Union[str, int]]) - A dictionary of group information.person_properties?(dict[str, Any]) - A dictionary of person properties.group_properties?(dict[str, dict[str, Any]]) - A dictionary of group properties.only_evaluate_locally(bool