PostHog Python SDK

Getting started

The Python SDK captures events, evaluates feature flags and reports errors from Python 3.10 or later.

To send your first event, install the package, create a client, capture an event, and shut the client down, as the steps below show.

Install

Terminal
pip install "posthog>=8,<9"

Initialize

Create one client for your app with your project token and host. Your project token and host are in your project settings. Keep the token in an environment variable rather than in code.

Python
from posthog import Posthog
posthog = Posthog("<ph_project_token>", host="https://us.i.posthog.com")

Capture an event

Python
posthog.capture("user_signed_up", distinct_id="user_123", properties={"plan": "free"})

capture queues the event and returns right away. A background thread sends it.

Share context across calls

Open a context with new_context() or @scoped(). Every event, exception, flag evaluation, and span inside shares the same user ID, session ID, and tags.

Python
with posthog.new_context():
posthog.identify_context("user_123")
posthog.tag("plan", "pro")
posthog.capture("checkout_started")
  • Open a context first. identify_context(), tag(), and set_context_*() silently do nothing outside new_context() or @scoped().
  • Isolate requests and jobs. Pass fresh=True at request or worker boundaries, so parent state doesn't leak. For web apps, use PosthogASGIMiddleware (FastAPI, Starlette, ASGI) or PosthogContextMiddleware (Django).
  • Use with AsyncPosthog. Contexts live in contextvars, so from posthog import new_context, identify_context, tag and PosthogASGIMiddleware apply to AsyncPosthog calls too.

Shut down

Call shutdown() before your process exits, so queued events are sent.

Python
posthog.shutdown()

In an asyncio app, use AsyncPosthog as an async context manager instead. See AsyncClient.

Use AsyncPosthog in FastAPI

Keep one AsyncPosthog client for the lifetime of your app. A FastAPI lifespan handler does this.

Python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from posthog import AsyncPosthog
from posthog.integrations.asgi import PosthogASGIMiddleware
@asynccontextmanager
async def lifespan(app: FastAPI):
async with AsyncPosthog("<ph_project_token>", host="https://us.i.posthog.com") as posthog:
app.state.posthog = posthog
yield
app = FastAPI(lifespan=lifespan)
app.add_middleware(PosthogASGIMiddleware)

The posthoganalytics package

posthoganalytics is the same SDK under another module name. Use it when another module named posthog is on your import path.

Setup

Client(...)

Python
Client(project_api_key: str, host=None, *, debug=False, max_queue_size=10000, send=True, on_error=None, flush_at=100, flush_interval=5.0, max_retries=3, sync_mode=False, timeout: float = 15, thread=1, poll_interval=30, personal_api_key=None, disabled=False, disable_geoip=True, is_server=True, historical_migration=False, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries=1, super_properties=None, super_options=None, enable_exception_autocapture=False, log_captured_exceptions=False, project_root=None, privacy_mode=False, before_send=None, flag_fallback_cache_url=None, enable_local_evaluation=True, flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None, capture_exception_code_variables=False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: list[str] | None = None, enable_exception_autocapture_rate_limiting=False, exception_autocapture_bucket_size=ExceptionCapture.DEFAULT_BUCKET_SIZE, exception_autocapture_refill_rate=ExceptionCapture.DEFAULT_REFILL_RATE, exception_autocapture_refill_interval_seconds=ExceptionCapture.DEFAULT_REFILL_INTERVAL_SECONDS, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = _AI_MAX_PROPERTIES_SIZE, secret_key=None, metrics: Optional[dict] = None, enable_full_ai_capture=False, capture_trace_context=False, traces: Optional[dict] = None, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None)

Initialize a new PostHog client instance.

Parameters:

NameDescription
project_api_keystr. PostHog project API key/token. Required.
hostPostHog host. Defaults to the US ingestion endpoint when not set. App hosts such as https://us.posthog.com are mapped to the corresponding ingestion host. Default: None.
debugEnable verbose SDK logging and re-raise errors from public API methods. Default: False.
max_queue_sizeMaximum number of analytics events buffered before upload. AI events use capture_ai_max_queue_size. Default: 10000.
sendIf False, queueing succeeds but events are not sent. Default: True.
on_errorOptional callback (error, batch) invoked when an upload fails: by background consumers, or on the calling thread in sync_mode. Capture failures arrive as CaptureError. Without it, each failed batch logs one aggregate line. A capture that fails inside the callback logs that line instead of calling it again. Keep it short and non-blocking. Calling lifecycle methods directly is safe and deferred, but do not start another thread or task that calls flush(), join(), or shutdown() and then wait for it from the callback. Default: None.
flush_atNumber of queued events that triggers a batch upload. Default: 100.
flush_intervalMaximum seconds a background consumer waits before flushing a partial batch. Default: 5.0.
max_retriesNumber of upload retries. Values below 0 are treated as 0. Default: 3.
sync_modeIf True, send each event synchronously instead of using background worker threads. This blocks the calling thread; in asyncio applications such as FastAPI, use AsyncPosthog instead. Default: False.
timeoutfloat. HTTP request timeout in seconds for event uploads. Default: 15.
threadNumber of background consumer threads. Default: 1.
poll_intervalSeconds between local feature flag definition refreshes. Default: 30.
secret_keyA Personal API Key or Project Secret API Key, used to authenticate local feature flag evaluation, remote config payloads, and decrypted flag payloads. emails needs a Project Secret API Key with the transactional_email:write scope to send, and transactional_email:read or transactional_email:write for emails.get. Keep it on your server. For example, posthog.Client(project_api_key, secret_key="phs_..."). Default: None.
personal_api_keyDeprecated alias for secret_key. Still honored for backwards compatibility; prefer secret_key, which also accepts a Project Secret API Key. Default: None.
disabledIf True, disable captures and API requests. Useful in tests. Default: False.
disable_geoipWhether to disable server-side GeoIP enrichment. Defaults to True. Events get $geoip_disable only when the event, context tags and super_properties leave it unset. Set disable_geoip=False (or $geoip_disable: False on the event) and pass $ip in event properties to geolocate from a client IP. Default: True.
is_serverWhether 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. Events get $is_server only when the event, context tags and super_properties leave it unset. Default: True.
historical_migrationMark events as historical migration imports. Pass past timestamp values on those capture() calls. Default: False.
feature_flags_request_timeout_secondsfloat. Timeout in seconds for feature flag and remote config requests. Default: 3.
feature_flags_request_max_retriesNumber of retries for feature flag requests after network, transport, or timeout failures. Defaults to 1. Set to 0 to disable retries. Default: 1.
app_hostOptional[str]. Your PostHog app host, such as https://posthog.example.com. emails sends there. Needed only when host is not PostHog Cloud, for example a reverse proxy, which must not receive the secret key, or a self-hosted PostHog. emails is the only part of this client that uses app_host. Feature flag methods, such as get_feature_flag, feature_enabled and evaluate_flags, load flag definitions from host with secret_key, even with enable_local_evaluation=False, and get_remote_config_payload sends it to host too. With enable_local_evaluation=True, a process forked after this client is created, such as a gunicorn or Celery worker, polls host with it. When host must not see the key, send email from a standalone posthog.emails.Emails(secret_key, host=app_host) and leave secret_key off this client. Default: None.
email_request_timeout_secondsfloat. Timeout in seconds for each email send request. Defaults to 15. Default: 15.
email_request_max_retriesint. Number of retries for an email send after a network error, a rate limit, or an unavailable service. Defaults to 2. Set to 0 when a job runner already retries the send. See posthog.emails.Emails for which errors retry and the backoff. Default: 2.
migrated_fromOptional[str]. The email provider you moved from, such as "resend". emails sends it with every request. Default: None.
super_propertiesProperties for every captured event. They fill only keys the event leaves unset, before before_send runs. $set, $set_once, $groups and $group_set fill one level deep. An event's own properties and context tags override them, and before_send can change or remove them. Default: None.
super_optionsCapture options for every captured event, such as {"cookieless_mode": True}. They fill only options the event leaves unset, before before_send runs. An event's own options and context options override them, and before_send can change them. They never set process_person_profile on identify-style events, such as $identify or $set, whose distinct ID the SDK did not generate: those default it to True. Default: None.
enable_exception_autocaptureAutomatically capture uncaught exceptions. Default: False.
log_captured_exceptionsAlso log exceptions captured by error tracking. Default: False.
project_rootRoot path used to determine in-app stack frames for captured exceptions. Defaults to the current working directory. Default: None.
privacy_modeFor AI observability, capture usage metadata without prompt inputs or outputs. Default: False.
enable_full_ai_captureCapture full AI content in PostHog AI wrapper events: skips string truncation and passes media (base64/data URIs) through unredacted. privacy_mode always wins. Wrapper events use the AI capture endpoint whether or not this is set. Defaults to False. Default: False.
before_sendOptional callback that can modify or drop events before upload. Return None to drop an event. Context tags, context options, super_properties, super_options and the values the SDK adds, such as $is_server, $geoip_disable and $os, fill in before it runs, so it can change or remove them. If before_send raises or returns a non-dict, the SDK logs the error and drops the event. A hook returning a new dict must copy event["options"] to preserve capture options. Default: None.
flag_fallback_cache_urlOptional feature flag fallback cache URL, such as memory://local/?ttl=300&size=10000 or a Redis URL. Default: None.
enable_local_evaluationWhether to poll feature flag definitions for local evaluation when secret_key is configured with a personal API key or project secret API key. Default: True.
flag_definition_cache_providerOptional[FlagDefinitionCacheProvider]. Optional external cache provider for sharing feature flag definitions across workers, such as in Redis, rather than polling in each worker. Default: None.
capture_exception_code_variablesCapture local variable values on exception stack frames. Default: False.
capture_trace_contextWhen OpenTelemetry is installed and a valid span is active at capture time, add its trace and span IDs as $trace_id and $span_id properties to events captured with capture() and capture_ai(), so they can be correlated with backend traces. They fill after context tags and super_properties, before before_send. A $trace_id or $span_id from the event, a context tag or super_properties stops the SDK adding either ID. Exception events (capture_exception) always attach these IDs regardless of this setting. Defaults to False. Default: False.
tracesOptional[dict]. Config dict for distributed tracing. Non-empty string values for service.name, service.version and deployment.environment in resource_attributes take precedence over service_name, service_version and environment, respectively. Options include 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_send is a callable, or a list run in order, that receives each finished span as a dict (trace_id, span_id and parent_span_id are read-only) and returns it, edited, or None to drop it; a hook that raises drops the span. The span dict has name, kind, status, attributes, events, start_time_ns, end_time_ns, trace_id, span_id and parent_span_id, and its attributes are plain Python values. The hook runs after posthogDistinctId and sessionId are attached, so it can scrub them. It must be a regular function. An async hook drops every span. In a list of hooks, the first one to return None stops the chain. An entry that isn't callable turns tracing off for the client. Past a per-span cap, the earliest attributes and events are kept and the span reports how many were dropped. posthogDistinctId and sessionId don't count toward the attribute cap and are never dropped. max_attribute_value_length also applies to strings nested in lists and dictionaries. All caps are applied again after before_span_send. Spans beyond max_queue_size are dropped. An invalid value falls back to its default with a warning. Tracing is off until this is provided. Spans export on a background timer even with sync_mode; serverless handlers should call flush() before returning. Defaults to None. Default: None.
code_variables_mask_patternsVariable-name patterns to mask when capturing code variables. Default: None.
code_variables_ignore_patternsVariable-name patterns to omit when capturing code variables. Default: None.
code_variables_mask_url_credentialsScrub credentials embedded in URLs/DSNs (e.g. user:pass@host) from captured code variables, regardless of the surrounding variable name. Defaults to True. Default: None.
code_variables_detect_secretsLast-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. Default: None.
in_app_moduleslist[str] | None. Module/package prefixes treated as in-app frames in captured exceptions. Default: None.
enable_exception_autocapture_rate_limitingRate limit autocaptured exceptions client-side with a token bucket per exception type. Disabled by default. Default: False.
exception_autocapture_bucket_sizeMaximum burst of autocaptured exceptions allowed per exception type (token bucket size, clamped to 0-100). Default: DEFAULT_BUCKET_SIZE.
exception_autocapture_refill_rateTokens restored per refill interval for each exception type's bucket. Default: DEFAULT_REFILL_RATE.
exception_autocapture_refill_interval_secondsSeconds between token refills for autocaptured exception rate limiting. Default: DEFAULT_REFILL_INTERVAL_SECONDS.
capture_compressionOptional[Union[CaptureCompression, str]]. Request-body compression for capture() uploads. CaptureCompression.GZIP, DEFLATE or ZSTD (or the strings "gzip", "deflate" or "zstd"). ZSTD needs pip install posthog[zstd]. When omitted, the POSTHOG_CAPTURE_COMPRESSION env var is consulted, then no compression. Default: None.
capture_ai_compressionOptional[Union[CaptureCompression, str]]. Request-body compression for capture_ai() uploads, set independently of capture_compression. Defaults to no compression, and the env var does not apply. CaptureCompression.ZSTD suits large AI payloads. Default: None.
capture_ai_max_queue_sizeint. Maximum number of AI events buffered before upload. Defaults to 1000, lower than max_queue_size because AI events are much larger. Default: 1000.
capture_ai_timeoutfloat. Seconds allowed for one AI upload request. Defaults to 30, longer than timeout because AI batches are much larger. Default: 30.
capture_ai_max_event_bytesint. Largest serialized size of an AI event's properties the SDK sends, measured like PostHog's per-event AI cap. A larger event is sent without its content properties when that fits, and otherwise dropped with an error log. Defaults to that cap, 8 MiB, and may only be lowered. Default: AI_MAX_PROPERTIES_SIZE.

Examples:

Python
from posthog import Posthog
posthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')

Capture

Client.capture

Python
capture(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Captures an event manually. Learn about capture best practices

Set special properties and identity behavior with their dedicated methods or options:

  • User identity. Pass distinct_id on this call, or call identify_context() inside new_context() to tag every event in the block.
  • Person properties. Call set() or set_once(), or pass $set and $set_once inside properties.
  • Groups. Pass groups={"company": "company_id"} to link the event to a group, and call group_identify() to set properties on that group.
  • Personless events. Omit distinct_id outside an identified context, or pass options={"process_person_profile": False} when supplying a distinct_id.

Parameters:

NameDescription
eventstr. The event name to capture. Required.
distinct_idThe distinct ID of the user.
propertiesA dictionary of properties to include with the event.
timestampThe timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
uuidA 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.
groupsA dictionary of group information. It merges into a $groups property and wins key by key.
flagsA FeatureFlagEvaluations snapshot from evaluate_flags(). The exact values from the snapshot are attached with no extra /flags request.
send_feature_flagsDeprecated. Prefer flags=... from evaluate_flags(). When truthy, evaluates flags during capture and attaches them to the event.
disable_geoipWhether to disable GeoIP for this event. It wins over a $geoip_disable in context tags or super_properties. A $geoip_disable property in this call's properties wins over it.
optionsCapture options for this event, such as {"process_person_profile": False}. Sent as given, for PostHog to validate. They override context options and super_options, which fill in before before_send runs. An option overrides its legacy $ property, such as $process_person_profile. A None option counts as unset. An identify-style event, such as $identify or $set, gets process_person_profile: True when this call leaves it unset, unless the SDK generated its distinct ID.

Examples:

Python
# Anonymous event
posthog.capture('some-anon-event')
posthog.capture('background-job', distinct_id='user_123', options={'process_person_profile': False})
Python
# 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')
Python
# Set event properties
posthog.capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true",
"$set": {"name": "Max Hedgehog"}
}
)
Python
# Page view event
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})

Identify

Client.set

Python
set(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Set properties on a person profile.

Uses identify_context() when distinct_id is omitted, and folds active context tags into $set. Without a distinct ID (explicit or from identify_context()), the call sends nothing and returns None.

Parameters:

NameDescription
distinct_idThe distinct ID of the user.
propertiesA dictionary of properties to set.
timestampThe timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
uuidA 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_geoipWhether to disable GeoIP for this event.
optionsCapture options for this event, sent as given. process_person_profile defaults to True.

Examples:

Python
# Set with distinct id
posthog.set(distinct_id='user123', properties={'name': 'Max Hedgehog'})

Note: Errors are logged rather than raised unless debug=True.

Client.set_once

Python
set_once(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Set properties on a person profile only if they haven't been set before.

Follows the same context distinct_id and tag rules as set(), without overwriting existing person properties.

Parameters:

NameDescription
distinct_idThe distinct ID of the user.
propertiesA dictionary of properties to set once.
timestampThe timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
uuidA 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_geoipWhether to disable GeoIP for this event.
optionsCapture options for this event, sent as given. process_person_profile defaults to True.

Examples:

Python
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})

Note: Errors are logged rather than raised unless debug=True.

Traces

Client.start_span

Python
start_span(name: str, *, kind: Optional[str] = None, attributes: Optional[Mapping[str, Any]] = None, parent: Union[Span, str, None] = None, tracestate: Optional[str] = None, start_time: Union[datetime, float, None] = None) -> Span

Start a span for distributed tracing. Alpha.

The span API is experimental and can change in a minor release. Spans already sent are kept; the SDK API isn't frozen yet.

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. At max_live_spans open spans, the SDK first evicts spans open longer than max_span_age seconds, which are never exported. If it is still at the limit, the returned span isn't recorded.

Parameters:

NameDescription
namestr. A low-cardinality operation name, e.g. GET /users/:id. Variable values belong in attributes, not the name. Required.
kindOptional[str]. internal (default), server, client, producer or consumer. Default: None.
attributesOptional[Mapping[str, Any]]. Initial attributes. Default: None.
parentUnion[Span, str, None]. A span handle, or an inbound W3C traceparent header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork. The active span is tracked with contextvars, so it carries across await. Threads don't reliably inherit it, so pass parent=span in a thread or a ThreadPoolExecutor task. A malformed traceparent starts a new trace and doesn't raise. A continued trace propagates the sampled flag it received. PostHog doesn't sample, so the span is exported whichever way the flag is set. Default: None.
tracestateOptional[str]. The inbound tracestate header accompanying a traceparent string parent; preserved and propagated. Default: None.
start_timeUnion[datetime, float, None]. A datetime or epoch seconds, to backdate the span. PostHog clamps a start time more than 24 hours old to the receive time. Default: None.

Examples:

Python
posthog = Posthog("<ph_project_api_key>", 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()}

Client.get_active_span

Python
get_active_span() -> Optional[Span]

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.

Examples:

Python
span = posthog.get_active_span()
if span is not None:
headers["traceparent"] = span.traceparent()

Alias

Client.alias

Python
alias(previous_id: ID_TYPES, distinct_id: Optional[str], timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[str] = None, disable_geoip: Optional[bool] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Create an alias between two distinct IDs.

Never alias users to a shared placeholder ID such as "anonymous".

Parameters:

NameDescription
previous_idID_TYPES. The previous distinct ID. Required - the call is dropped with a warning if it is missing or empty. Required.
distinct_idOptional[str]. The new distinct ID to alias to. Required - the call is dropped with a warning if it is missing or empty. The context distinct ID is never used here. Required.
timestampOptional[Union[datetime, str]]. The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. Default: None.
uuidOptional[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. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this event. Default: None.
optionsOptional[Dict[str, Any]]. Capture options for this event, sent as given. process_person_profile is True unless this call sets it. Default: None.

Examples:

Python
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')

Note: Errors are logged rather than raised unless debug=True.

Capture AI

Client.capture_ai

Python
capture_ai(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

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.

Use the posthog.ai wrappers for OpenAI, Anthropic, Gemini, LangChain, and OpenTelemetry rather than building $ai_* payloads by hand.

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, with one exception: an event over capture_ai_max_event_bytes is sent without $ai_input, $ai_output, $ai_output_choices, $ai_input_state, $ai_output_state and $ai_tools, and with $ai_content_removal_reason="event_too_large" and $ai_event_bytes_before_removal added. It is dropped with an error log if it is still too large.

Capture exception

Client.capture_exception

Python
capture_exception(exception: Optional[ExceptionArg], *, level: Optional[str] = None, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture an exception for error tracking. Never raises, even when debug=True.

Duplicate calls on the same exception instance send only one event.

Contexts only autocapture uncaught exceptions escaping new_context(), so call capture_exception() manually when catching and handling an error gracefully. Passing None reads sys.exc_info().

Returns the event UUID, or None if skipped or dropped.

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, unless the event, a context tag or super_properties sets either one.

Parameters:

NameDescription
exceptionOptional[ExceptionArg]. The exception to capture, or None to read sys.exc_info(). Required.
levelOptional[str]. The $exception_level, such as "warning" or "fatal". Defaults to "error". An unknown value counts as unset. Default: None.
distinct_idThe distinct ID of the user.
propertiesA dictionary of additional properties. Reserved exception properties, such as $exception_list and $exception_level, are ignored.
flagsA FeatureFlagEvaluations snapshot from evaluate_flags(). Attaches those exact flag values to the captured $exception event.
send_feature_flagsDeprecated. Pass flags from evaluate_flags() instead.
disable_geoipWhether to disable GeoIP for this event.

Examples:

Python
try:
# Some code that might fail
pass
except Exception as e:
posthog.capture_exception(e, distinct_id='user_distinct_id', properties=additional_properties)

Emails

Client.emails

Python
emails: Emails

Send transactional email from PostHog email templates or from content in your code, and read the status of each email sent with get.

Needs secret_key, a project secret API key with the transactional_email:write scope. Template sends need SDK 7.81.0 or later, and sends from code 7.84.0 or later. Emails.send lists each field and the version it needs. Use 8.0.2 or later, because earlier versions call /api/projects/@current/... paths, which PostHog is removing.

Sends go to app_host, or to the PostHog Cloud app host of host. For any other host, such as a reverse proxy or a self-hosted PostHog, set app_host, or each call raises EmailError with code missing_app_host.

Each request times out after email_request_timeout_seconds, 15 by default. A send retries up to email_request_max_retries times, 2 by default, with the same idempotency key. Emails lists the errors it retries and the backoff. A disabled or shut-down client sends nothing.

Examples:

Python
client.emails.send(
to="user@example.com",
template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
template_data={"name": "Ada"},
distinct_id="user_123",
)

Flush

Client.flush

Python
flush(timeout_seconds: Optional[float] = 10) -> None

Attempt immediate delivery of queued events, ended spans and autocaptured metrics, keeping the client reusable.

For a client shared across requests or serverless invocations (including the module-level client), call flush() before a short-lived invocation returns. Use shutdown() instead only for final process cleanup or when disposing of 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 the consumers. Calls made directly from SDK callbacks such as on_error are deferred rather than blocking the worker that invoked the callback.

Parameters:

NameDescription
timeout_secondsOptional[float]. Seconds to wait for event queues to drain, shared across event lanes. Defaults to 10 seconds. Pass None to wait without a time limit; this does not guarantee successful delivery. Queued spans flush concurrently. The span exporter waits up to this many seconds for an in-flight flush, then uses a fresh drain budget once it acquires the lock. If the lock wait times out, the in-flight flush is left 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. Each span request is bounded by the client's timeout in seconds, and the last request is not cut short. This is therefore not a strict wall-clock limit for the whole call. With None, a retriable span failure is left for a later flush rather than retried within this call. Default: 10.

Examples:

Python
posthog.capture('event_name', distinct_id='user_id')
# Before a serverless invocation returns; keep the shared client open.
posthog.flush(timeout_seconds=10)

Get feature flag

Client.get_feature_flag

Python
get_feature_flag(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FlagValue]

Get multivariate feature flag value for a user.

get_feature_flag is deprecated and will be removed in a future major version. Use posthog.evaluate_flags(distinct_id, ...) and call flags.get_flag(key) instead. This consolidates flag evaluation into a single /flags request per incoming request.

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
send_feature_flag_eventsbool. Whether to send feature flag events. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
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 payload

Client.get_feature_flag_payload

Python
get_feature_flag_payload(key: str, distinct_id: ID_TYPES, *, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[object]

Get the payload for a feature flag.

get_feature_flag_payload is deprecated and will be removed in a future major version. Use posthog.evaluate_flags(distinct_id, ...) and call flags.get_flag_payload(key) instead. This consolidates flag evaluation into a single /flags request per incoming request.

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The distinct ID of the user. Required.
match_valueOptional[FlagValue]. The specific flag value to get payload for. Default: None.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
send_feature_flag_eventsbool. Deprecated. Use get_feature_flag() instead if you need events. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Returns:

TypeDescription
Optional[object]The payload associated with the matched feature flag value, or None. This method returns the payload only, not the FeatureFlagResult wrapper used internally to compute it.

Examples:

Python
flags = posthog.evaluate_flags('distinct_id_of_your_user')
if flags.is_enabled('flag-key'):
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = flags.get_flag_payload('flag-key')

Get feature flag result

Client.get_feature_flag_result

Python
get_feature_flag_result(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FeatureFlagResult]

Get a FeatureFlagResult object which contains the flag result and payload for a key by evaluating locally or remotely depending on whether local evaluation is enabled and the flag can be locally evaluated. This also captures the $feature_flag_called event unless send_feature_flag_events is False. When the flag's config version 2 record is a complete experiment split (an experiment rule with a rule ID and a variant key), it also captures the $experiment_exposure event, once per distinct ID, groups, flag, rule and variant.

Examples:

Python
flag_result = posthog.get_feature_flag_result('flag-key', 'distinct_id_of_your_user')
if flag_result and flag_result.get_value() == 'variant-key':
# Do something differently for this user
# Optional: fetch the payload
matched_flag_payload = flag_result.payload

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
send_feature_flag_eventsbool. Whether to send feature flag events. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Returns:

TypeDescription
Optional[FeatureFlagResult]Optional[FeatureFlagResult]: The evaluated result, including a healthy disabled flag, or None when no result is available (for example, a missing flag or a server-marked failure without a successful fallback).

Get feature flags

Client.get_feature_variants

Python
get_feature_variants(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> dict[str, Union[bool, str]]

Get feature flag variants for a user.

Parameters:

NameDescription
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Client.get_all_flags

Python
get_all_flags(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> Optional[dict[str, Union[bool, str]]]

Get all feature flags for a user.

Parameters:

NameDescription
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
posthog.get_all_flags('distinct_id_of_your_user')

Get feature flags and payloads

Client.get_feature_flags_and_payloads

Python
get_feature_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsAndPayloads

Get feature flags and payloads for a user.

Parameters:

NameDescription
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
result = posthog.get_feature_flags_and_payloads('<distinct_id>')

Client.get_all_flags_and_payloads

Python
get_all_flags_and_payloads(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsAndPayloads

Get all feature flags and their payloads for a user.

Parameters:

NameDescription
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')

Evaluate flags

Client.evaluate_flags

Python
evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[List[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations

Evaluate all feature flags for a user in a single call and return a FeatureFlagEvaluations snapshot. Branch on .is_enabled() / .get_flag() and pass the same snapshot to 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".

Scope which evaluated flags attach to capture() with these helpers:

  • capture(..., flags=flags) attaches every evaluated flag in the snapshot.
  • capture(..., flags=flags.only_accessed()) attaches only flags read via is_enabled() or get_flag() before that call.
  • capture(..., flags=flags.only(["flag-key"])) attaches only the listed flag keys.

Calling get_flag_payload() doesn't mark a flag accessed or emit $feature_flag_called.

Parameters:

NameDescription
distinct_idOptional[ID_TYPES]. The user's distinct ID. If None, falls back to the context distinct_id. If still unresolvable, returns an empty snapshot. Default: None.
groupsOptional[Mapping[str, Union[str, int]]]. Mapping of group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties for conditions not yet ingested or overridden locally. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties keyed by group type rather than group key, such as {"company": {"plan": "enterprise"}}. Default: None.
only_evaluate_locallybool. If True, never fall back to remote evaluation — flags that can't be evaluated locally are omitted from the snapshot and listed with a reason in its unresolved_flags. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
flag_keysOptional[List[str]]. Optional list that scopes local evaluation, the underlying /flags request, and the returned snapshot. When omitted or None, 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 per evaluate_flags call unless only_evaluate_locally is True. If the server also does not know the key, it is omitted from the snapshot. Default: None.
device_idOptional[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. Default: None.

Returns:

TypeDescription
FeatureFlagEvaluationsA FeatureFlagEvaluations snapshot.

Examples:

Python
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)

Group identify

Client.group_identify

Python
group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[Union[str, UUID]] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Identify a group and set its properties.

Requires the Group Analytics add-on. Pass name in properties to set the group's display name in PostHog, and pass groups={group_type: group_key} on capture() to link events to the group.

Parameters:

NameDescription
group_typestr. The type of group (e.g., 'company', 'team'). Required - the call is dropped with a warning if it is missing or empty. Required.
group_keystr. The unique identifier for the group. Required - the call is dropped with a warning if it is missing or empty. Required.
propertiesOptional[Dict[str, Any]]. A dictionary of properties to set on the group. Default: None.
timestampOptional[Union[datetime, str]]. The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. Default: None.
uuidOptional[Union[str, UUID]]. 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. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this event. Default: None.
distinct_idOptional[ID_TYPES]. The distinct ID of the user performing the action. Falls back to the context distinct ID, then to $<group_type>_<group_key>. Default: None.
optionsOptional[Dict[str, Any]]. Capture options for this event, sent as given. process_person_profile is True unless this call sets it. Default: None.

Examples:

Python
posthog.group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})

Note: Errors are logged rather than raised unless debug=True.

Is feature enabled

Client.feature_enabled

Python
feature_enabled(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[bool]

Check if a feature flag is enabled for a user.

feature_enabled is deprecated and will be removed in a future major version. Use posthog.evaluate_flags(distinct_id, ...) and call flags.is_enabled(key) instead. This consolidates flag evaluation into a single /flags request per incoming request.

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
only_evaluate_locallybool. Whether to only evaluate locally. Default: False.
send_feature_flag_eventsbool. Whether to send feature flag events. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
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')

Shutdown

Client.join

Python
join() -> None

Attempt to process queued events and end the consumer threads. Do not use directly, call shutdown() instead.

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.

Examples:

Python
posthog.join()

Client.shutdown

Python
shutdown() -> None

Attempt final delivery and permanently shut down the client.

Call this for final process cleanup or when disposing of a client that will not be reused. It closes capture lanes, stops background workers and the feature flag poller, and tears down integrations. Do not call it at the end of each request or serverless invocation when the client is shared; call flush() before returning instead. A shut-down client cannot be reused; create a new client if needed.

Normally this method 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 one 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. Any spans it cannot send are discarded with a warning, as are spans still open. A script that exits without calling shutdown() gets only a brief best-effort span flush, so don't rely on it. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. When called directly from an SDK callback such as on_error, shutdown is deferred to avoid blocking the worker that invoked the callback. If the callback must coordinate a blocking shutdown, have it signal an application-owned thread and return before that thread calls shutdown. Do not wait inside the callback for another thread or task that calls a lifecycle method.

Examples:

Python
posthog.shutdown()

Flag definition loader

Client.load_feature_flags

Python
load_feature_flags()

Load feature flags for local evaluation.

Requires secret_key. Fetches definitions synchronously on the calling thread, and starts background polling every poll_interval seconds when enable_local_evaluation=True.

Examples:

Python
posthog.load_feature_flags()

Client.feature_flag_definitions

Python
feature_flag_definitions()

Return feature flag definitions loaded for local evaluation.

Returns:

TypeDescription
  • | The currently loaded feature flag definitions, or None before local evaluation has loaded definitions.

SDK utils

Client.queue

Python
queue: Queue

The analytics lane's queue (kept for backwards compatibility).

Client.consumers

Python
consumers: Optional[List[Consumer]]

Flat list of the lanes' consumers, analytics first (kept for backwards compatibility).

Client.new_context

Python
new_context(fresh=False, capture_exceptions: Optional[bool] = None)

Create a new context for managing shared state. Learn more about contexts.

Contexts store identity, session ID, options, and tags in contextvars across calls and await, then clear on exit. identify_context(), tag(), and set_context_*() silently do nothing outside a context.

Parameters:

NameDescription
freshWhether to create a fresh context that doesn't inherit from parent. Default: False.
capture_exceptionsOptional[bool]. Whether to automatically capture exceptions in this context. If omitted, defaults to this client's exception autocapture setting. Default: None.

Examples:

Python
with client.new_context():
client.identify_context('<distinct_id>')
client.capture('event_name')

Client.scoped

Python
scoped(fresh=False, capture_exceptions: Optional[bool] = None)

Decorator that creates a new context for the wrapped function using this client.

Works on both sync and async def functions. Put scoped closest to the function when stacking decorators.

Parameters:

NameDescription
freshWhether to create a fresh context that doesn't inherit from parent. Default: False.
capture_exceptionsOptional[bool]. Whether to automatically capture exceptions in this context. If omitted, defaults to this client's exception autocapture setting. Default: None.

Client.tag

Python
tag(name: str, value: Any) -> None

Add a tag to the current context.

Every event and exception captured in this context includes this key-value pair in its properties. Calling set() or set_once() in the context also saves active tags as person properties.

If the same key appears in multiple places, explicit properties on the call win over context tags, and context tags win over super_properties.

Calls outside new_context() or @scoped() do nothing.

Parameters:

NameDescription
namestr. The tag key. Required.
valueAny. The tag value. Required.

Client.get_tags

Python
get_tags() -> Dict[str, Any]

Get all tags from the current context.

Returns:

TypeDescription
Dict[str, Any]Dict of all tags in the current context.

Client.set_context_option

Python
set_context_option(key: str, value: Any) -> None

Set a capture option for every event captured within the current context.

Context options fill options an event leaves unset, before before_send runs, so the hook sees them. They override super_options. An event's own options override them, and before_send can change them. They never set process_person_profile on identify-style events, such as $identify or $set, whose distinct ID the SDK did not generate: those default it to True.

Parameters:

NameDescription
keystr. The option name, such as "process_person_profile". Required.
valueAny. The option value, sent as given. Required.

Client.get_context_options

Python
get_context_options() -> Dict[str, Any]

Get all capture options from the current context.

Returns:

TypeDescription
Dict[str, Any]Dict of all capture options in the current context.

Client.identify_context

Python
identify_context(distinct_id: str) -> None

Identify the current context with a distinct ID.

In Python SDK 6.0.0 and later, user identification uses the contexts pattern rather than a separate identify() method.

Call this method inside new_context(), and every event, exception, flag evaluation, and span in that context is automatically tagged with this distinct_id. Calls outside a context do nothing.

Parameters:

NameDescription
distinct_idstr. The distinct ID to associate with the current context and its children. Required.

Client.set_context_session

Python
set_context_session(session_id: str) -> None

Set the session ID for the current context.

Session IDs must be valid UUIDv7 strings, such as X-POSTHOG-SESSION-ID from PostHog JS.

Parameters:

NameDescription
session_idstr. The session ID to associate with the current context and its children. Required.

Client.set_context_device_id

Python
set_context_device_id(device_id: str) -> None

Set the device ID for the current context.

Parameters:

NameDescription
device_idstr. The device ID to associate with the current context and its children. Required.

Client.feature_flags

Python
feature_flags

Get the local evaluation feature flags.

Client.get_feature_payloads

Python
get_feature_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> dict[str, Optional[str]]

Get feature flag payloads for a user, preserving valid serialized JSON.

Parameters:

NameDescription
distinct_idID_TYPES. The distinct ID of the user. Required.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
payloads = posthog.get_feature_payloads('<distinct_id>')

Client.get_flags_decision

Python
get_flags_decision(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsResponse

Get feature flags decision.

Parameters:

NameDescription
distinct_idOptional[ID_TYPES]. The distinct ID of the user. Default: None.
groupsOptional[Mapping[str, Union[str, int]]]. A dictionary of group information. Default: None.
person_propertiesOptional[Dict[str, Any]]. A dictionary of person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. A dictionary of group properties. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP for this request. Default: None.
flag_keys_to_evaluateOptional[list[str]]. A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. Default: None.
device_idOptional[str]. The device ID for this request. Default: None.

Examples:

Python
decision = posthog.get_flags_decision('user123')

Client.metrics

Python
metrics: PostHogMetrics

The posthog.metrics API: a statsd-style pre-aggregating metrics client — alpha.

Samples fold into per-series aggregates in memory and flush as one OTLP data point per series per window, so recording from hot paths is cheap. Configure via the metrics client option; pending metrics flush on shutdown().

Examples:

Python
client = Posthog("<ph_project_api_key>", metrics={"service_name": "billing-worker"})
client.metrics.count("invoices.processed", 1, attributes={"plan": "pro"})
client.metrics.gauge("queue.depth", 42)
client.metrics.histogram("job.duration", 187, unit="ms")

Client.get_remote_config_payload

Python
get_remote_config_payload(key: str)

Get the payload for a remote config feature flag.

Parameters:

NameDescription
keystr. The remote config feature flag key. Required.

Returns:

TypeDescription
  • | The payload associated with the feature flag, or None if the client is disabled, no secret_key is configured, or the request fails. Encrypted payloads are decrypted by PostHog before being returned.
Note

Requires secret_key for authentication.

Client.get_feature_flag_evaluation_runtime

Python
get_feature_flag_evaluation_runtime(key: str) -> Optional[FeatureFlagEvaluationRuntime]

Return where a locally loaded feature flag is meant to be evaluated.

Parameters:

NameDescription
keystr. The feature flag key. Required.

Returns:

TypeDescription
Optional[FeatureFlagEvaluationRuntime]The flag's evaluation runtime, or 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.

Examples:

Python
from posthog import FeatureFlagEvaluationRuntime
runtime = posthog.get_feature_flag_evaluation_runtime("my-flag")
if runtime is FeatureFlagEvaluationRuntime.SERVER:
...

Client.get_feature_flag_keys_by_evaluation_runtime

Python
get_feature_flag_keys_by_evaluation_runtime(evaluation_runtime: Union[FeatureFlagEvaluationRuntime, str]) -> list[str]

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:

NameDescription
evaluation_runtimeUnion[FeatureFlagEvaluationRuntime, str]. The runtime to match, as a FeatureFlagEvaluationRuntime or its string value. Required.

Returns:

TypeDescription
list[str]The matching flag keys, in the order local evaluation loaded them. Empty when no definitions are loaded.

Examples:

Python
from posthog import FeatureFlagEvaluationRuntime
client_keys = posthog.get_feature_flag_keys_by_evaluation_runtime(
FeatureFlagEvaluationRuntime.CLIENT
)

posthog.integrations.django.PosthogContextMiddleware

Python
PosthogContextMiddleware(get_response)

Middleware to automatically track Django requests.

Place this after AuthenticationMiddleware in Django's MIDDLEWARE list so request.user identity and email are available. In Django REST Framework apps, pair it with posthog.integrations.drf.exception_handler to capture handled API errors.

The middleware reads request.user before your view runs. After calling django.contrib.auth.login() in a login or signup view, call identify_context(str(user.pk)) or hook user_logged_in so events in that request attach to the user.

This middleware wraps all calls with a posthog context. It attempts to extract the following from the request:

  • Session ID, (extracted from X-POSTHOG-SESSION-ID)
  • Distinct ID, (extracted from X-POSTHOG-DISTINCT-ID, falling back to the authenticated request user ID)
  • Authenticated user email as email
  • Request URL as $current_url
  • Request method as $request_method
  • Request path as $request_path
  • Forwarded IP address as $ip
  • User agent as $user_agent

Configure the integration with these Django settings:

  • POSTHOG_MW_CLIENT: client used for automatic exception capture, or the global client. This does not redirect events explicitly captured through other clients.
  • POSTHOG_MW_CAPTURE_EXCEPTIONS: False enables context enrichment only; True enables automatic exception capture; None inherits the effective client's enable_exception_autocapture. When omitted, the legacy default is True.
  • POSTHOG_MW_REQUEST_FILTER: a callback receiving the request. Returning False disables both enrichment and automatic exception capture for that request.
  • POSTHOG_MW_EXTRA_PROPERTIES: a callback returning additional event properties.
  • POSTHOG_MW_CAPTURE_TRACING_HEADERS: read PostHog identity and session headers as request-scoped analytics context (default: True). Explicit capture IDs and event properties take precedence. These values are never authentication or authorization. Authenticated Django user identity remains the fallback when no usable header ID is available or header capture is disabled.
  • POSTHOG_MW_TRUST_TRACING_HEADERS: deprecated alias for POSTHOG_MW_CAPTURE_TRACING_HEADERS; the capture-named setting takes precedence.
  • POSTHOG_MW_PROPERTIES_MAP: an optional callback transforming request properties.

The old POSTHOG_MW_EXTRA_TAGS and POSTHOG_MW_TAG_MAP settings remain aliases; the property-named settings take precedence when both are configured.

Request properties are included on all events captured within the active context, including when automatic exception capture is disabled. See the context documentation for more information. The extracted distinct ID and session ID, if found, are used to associate all events captured in the middleware context with the same distinct ID and session as currently active on the frontend. See the documentation for set_context_session and identify_context for more details.

This middleware is hybrid-capable: it supports both WSGI (sync) and ASGI (async) Django applications. The middleware detects at initialization whether the next middleware in the chain is async or sync, and adapts its behavior accordingly. This ensures compatibility with both pure sync and pure async middleware chains, as well as mixed chains in ASGI mode.

Functions:

NameDescription
aextract_propertiesAsync version of extract_properties for use in async request handling.
aextract_request_userAsync version of extract_request_user for use in async request handling.
aextract_tagsCompatibility alias for aextract_properties.
extract_propertiesExtract event properties and identity from a synchronous request.
extract_request_userExtract user ID and email from request in sync context.
extract_tagsCompatibility alias for extract_properties.
process_exceptionProcess exceptions from views and downstream middleware.

Attributes:

NameTypeDescription
async_capable
capture_exceptionsOptional[bool]
capture_tracing_headers
client
extra_tagsCompatibility alias for extra_properties.
get_response
sync_capable
tag_mapCompatibility alias for properties_map.
trust_tracing_headersboolDeprecated alias for capture_tracing_headers.

Initialize the middleware with Django's next handler.

Parameters:

NameDescription
get_responseThe next middleware or view handler in Django's middleware chain. May be synchronous or asynchronous.

posthog.integrations.django.PosthogContextMiddleware.aextract_properties

Python
async aextract_properties(request)

Async version of extract_properties for use in async request handling.

Uses await request.auser() instead of request.user to avoid SynchronousOnlyOperation in async context.

Follows Django's naming convention for async methods (auser, asave, etc.).

posthog.integrations.django.PosthogContextMiddleware.aextract_request_user

Python
async aextract_request_user(request)

Async version of extract_request_user for use in async request handling.

Uses await request.auser() instead of request.user to avoid SynchronousOnlyOperation in async context.

Follows Django's naming convention for async methods (auser, asave, etc.).

posthog.integrations.django.PosthogContextMiddleware.aextract_tags

Python
async aextract_tags(request)

Compatibility alias for aextract_properties.

posthog.integrations.django.PosthogContextMiddleware.async_capable

Python
async_capable = True

posthog.integrations.django.PosthogContextMiddleware.capture_exceptions

Python
capture_exceptions: Optional[bool] = capture_exceptions if (capture_exceptions is None or isinstance(capture_exceptions, bool)) else True

posthog.integrations.django.PosthogContextMiddleware.capture_tracing_headers

Python
capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_headers, trust_tracing_headers, canonical_name='POSTHOG_MW_CAPTURE_TRACING_HEADERS', deprecated_name='POSTHOG_MW_TRUST_TRACING_HEADERS')

posthog.integrations.django.PosthogContextMiddleware.client

Python
client = cast('Optional[Client]', settings.POSTHOG_MW_CLIENT)

posthog.integrations.django.PosthogContextMiddleware.extra_tags

Python
extra_tags

Compatibility alias for extra_properties.

posthog.integrations.django.PosthogContextMiddleware.extract_properties

Python
extract_properties(request)

Extract event properties and identity from a synchronous request.

posthog.integrations.django.PosthogContextMiddleware.extract_request_user

Python
extract_request_user(request)

Extract user ID and email from request in sync context.

posthog.integrations.django.PosthogContextMiddleware.extract_tags

Python
extract_tags(request)

Compatibility alias for extract_properties.

posthog.integrations.django.PosthogContextMiddleware.get_response

Python
get_response = get_response

posthog.integrations.django.PosthogContextMiddleware.process_exception

Python
process_exception(request, exception)

Process exceptions from views and downstream middleware.

Django calls this WHILE still inside the context created by call, so request tags have already been extracted and set. This method just needs to capture the exception directly.

Django converts view exceptions into responses before they propagate through the middleware stack, so the context manager in call/acall never sees them.

Note: Django's process_exception is always synchronous, even for async views.

posthog.integrations.django.PosthogContextMiddleware.sync_capable

Python
sync_capable = True

posthog.integrations.django.PosthogContextMiddleware.tag_map

Python
tag_map

Compatibility alias for properties_map.

posthog.integrations.django.PosthogContextMiddleware.trust_tracing_headers

Python
trust_tracing_headers: bool

Deprecated alias for capture_tracing_headers.

posthog.integrations.drf.exception_handler

Python
exception_handler(exc: Exception, context: Mapping[str, Any]) -> Any

Capture handled DRF 5xx exceptions using DRF's default handler.

Keep PosthogContextMiddleware enabled alongside this handler for request context and unhandled exceptions.

Examples:

Python
# settings.py
REST_FRAMEWORK = {
"EXCEPTION_HANDLER": "posthog.integrations.drf.exception_handler",
}

posthog.integrations.drf.create_exception_handler

Python
create_exception_handler(handler: Optional[Callable[[Exception, Mapping[str, Any]], Any]] = None, *, client: Optional[Client] = None, capture_exceptions: Optional[bool] = None, capture_4xx: bool = False, exception_filter: Optional[Callable[[Exception, Any, Mapping[str, Any]], bool]] = None) -> Callable[[Exception, Mapping[str, Any]], Any]

Create a PostHog-instrumented DRF exception handler.

Parameters:

NameDescription
handlerOptional[Callable[[Exception, Mapping[str, Any]], Any]]. Handler to delegate to. Defaults to DRF's standard exception handler. Its return value and raised exceptions are preserved. Default: None.
clientOptional[Client]. Optional PostHog client. Client precedence is this argument, the legacy POSTHOG_DRF_CLIENT alias, POSTHOG_MW_CLIENT, then the global PostHog client. Default: None.
capture_exceptionsOptional[bool]. Whether to capture handled DRF exceptions. An explicit value takes precedence over POSTHOG_MW_CAPTURE_EXCEPTIONS. A boolean setting is used directly; an explicit None setting inherits the effective client's enable_exception_autocapture. An omitted or malformed setting preserves the legacy True default. Default: None.
capture_4xxbool. Also capture handled 4xx responses. Disabled by default to avoid reporting expected API errors. Default: False.
exception_filterOptional[Callable[[Exception, Any, Mapping[str, Any]], bool]]. Optional final filter called with (exception, response, context). Returning False suppresses capture. Default: None.

When POSTHOG_MW_REQUEST_FILTER is configured, it is also applied to the underlying Django request before capture so handled errors cannot bypass the middleware's per-request exclusion.

The delegated handler is called first. A None response is never captured here because DRF will re-raise that exception, allowing Django's middleware to capture it as unhandled.

posthog.integrations.flask.PosthogFlaskIntegration

Python
PosthogFlaskIntegration(app: Optional[Flask] = None, *, client: Optional[Client] = None, capture_exceptions: Optional[bool] = None, request_filter: Optional[Callable[[Request], bool]] = None, extra_properties: Optional[Callable[[Request], Mapping[str, Any]]] = None, trust_tracing_headers: Optional[bool] = None, capture_tracing_headers: Optional[bool] = None) -> None

Add PostHog request context and exception tracking to a Flask app.

Parameters:

NameDescription
appOptional[Flask]. An optional Flask application. If omitted, call init_app later (the Flask application-factory pattern). Default: None.
clientOptional[Client]. Optional destination for automatically captured exceptions. The global client is used by default. Request context still enriches events captured through any client and does not redirect capture calls. Default: None.
capture_exceptionsOptional[bool]. Capture exceptions that reach Flask's unhandled exception machinery. If omitted, inherit the effective client's enable_exception_autocapture setting. Pass True or False to override it. Default: None.
request_filterOptional[Callable[[Request], bool]]. Optional callback receiving Flask's request object. A false return value disables both context and exception capture for that request. Default: None.
extra_propertiesOptional[Callable[[Request], Mapping[str, Any]]]. Optional callback returning additional event properties. This is useful for application-specific metadata such as an authenticated user's role. Values should not contain secrets or request bodies. Default: None.
capture_tracing_headersOptional[bool]. Read PostHog distinct and session ID headers as request-scoped analytics context. Defaults to True. Explicit capture IDs and event properties take precedence. Never use these values for security. Default: None.
trust_tracing_headersOptional[bool]. Deprecated alias for capture_tracing_headers. The capture-named option takes precedence when both are supplied. Default: None.

The integration intentionally does not capture exceptions handled by an application error handler, expected HTTP exceptions, request or response bodies, query strings, cookies, authorization headers, or arbitrary headers. Call capture_exception explicitly from a custom error handler if a handled exception should be reported.

Functions:

NameDescription
init_appRegister the integration with a Flask application once.

Attributes:

NameTypeDescription
capture_exceptions
capture_tracing_headers
client
extra_properties
request_filter
trust_tracing_headersboolDeprecated alias for capture_tracing_headers.

posthog.integrations.flask.PosthogFlaskIntegration.capture_exceptions

Python
capture_exceptions = capture_exceptions

posthog.integrations.flask.PosthogFlaskIntegration.capture_tracing_headers

Python
capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_headers, trust_tracing_headers)

posthog.integrations.flask.PosthogFlaskIntegration.client

Python
client = client

posthog.integrations.flask.PosthogFlaskIntegration.extra_properties

Python
extra_properties = extra_properties

posthog.integrations.flask.PosthogFlaskIntegration.init_app

Python
init_app(app: Flask) -> None

Register the integration with a Flask application once.

posthog.integrations.flask.PosthogFlaskIntegration.request_filter

Python
request_filter = request_filter

posthog.integrations.flask.PosthogFlaskIntegration.trust_tracing_headers

Python
trust_tracing_headers: bool

Deprecated alias for capture_tracing_headers.

posthog.integrations.asgi.PosthogASGIMiddleware

Python
PosthogASGIMiddleware(app: _ASGIApp, client: Optional[Client] = None, capture_exceptions: Optional[bool] = None, request_filter: Optional[_RequestFilter] = None, extra_properties: Optional[_ExtraProperties] = None, trust_tracing_headers: Optional[bool] = None, *, capture_tracing_headers: Optional[bool] = None) -> None

Add PostHog context and automatic exception capture to an ASGI app.

It creates a context for each HTTP or WebSocket request and captures exceptions that escape the app. In FastAPI or Starlette, add it with app.add_middleware(PosthogASGIMiddleware, client=posthog). For Litestar, another ASGI framework or a raw ASGI app, wrap the app with app = PosthogASGIMiddleware(app, client=posthog).

Parameters:

NameDescription
app_ASGIApp. The downstream ASGI application. Required.
clientOptional[Client]. Optional destination for automatically captured exceptions. The global client is used by default. Request context still enriches events captured through any client and does not redirect capture calls. Default: None.
capture_exceptionsOptional[bool]. Capture exceptions escaping the downstream app. If omitted, inherit the effective client's enable_exception_autocapture setting. Pass True or False to override it. Default: None.
request_filterOptional[_RequestFilter]. Optional sync or async callback receiving the ASGI scope. Returning False bypasses all instrumentation for that scope. Default: None.
extra_propertiesOptional[_ExtraProperties]. Optional sync or async callback receiving the ASGI scope and returning additional event properties. Default: None.
capture_tracing_headersOptional[bool]. Read PostHog distinct and session ID headers as request-scoped analytics context. Defaults to True. Explicit capture IDs and event properties take precedence. Never use these values for security. Default: None.
trust_tracing_headersOptional[bool]. Deprecated alias for capture_tracing_headers. The capture-named option takes precedence when both are supplied. Default: None.

Attributes:

NameTypeDescription
app
capture_exceptions
capture_tracing_headers
client
extra_properties
request_filter
trust_tracing_headersboolDeprecated alias for capture_tracing_headers.

posthog.integrations.asgi.PosthogASGIMiddleware.app

Python
app = app

posthog.integrations.asgi.PosthogASGIMiddleware.capture_exceptions

Python
capture_exceptions = capture_exceptions

posthog.integrations.asgi.PosthogASGIMiddleware.capture_tracing_headers

Python
capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_headers, trust_tracing_headers)

posthog.integrations.asgi.PosthogASGIMiddleware.client

Python
client = client

posthog.integrations.asgi.PosthogASGIMiddleware.extra_properties

Python
extra_properties = extra_properties

posthog.integrations.asgi.PosthogASGIMiddleware.request_filter

Python
request_filter = request_filter

posthog.integrations.asgi.PosthogASGIMiddleware.trust_tracing_headers

Python
trust_tracing_headers: bool

Deprecated alias for capture_tracing_headers.

posthog.integrations.celery.PosthogCeleryIntegration

Python
PosthogCeleryIntegration(client: Optional[Client] = None, capture_exceptions: bool = True, capture_task_lifecycle_events: bool = True, propagate_context: bool = True, task_filter: Optional[Callable[[Optional[str], dict[str, Any]], bool]] = None)

Celery integration that captures task lifecycle events and exceptions.

Parameters:

NameDescription
clientOptional[Client]. Optional Client instance. When provided, all events and exceptions are captured through this client rather than the global posthog module. Don't skip this if using a custom flag definition cache provider, and pass the custom Client instance here initialized with the custom provider so fork safety for that provider is handled correctly. Default: None.
capture_exceptionsbool. Whether to capture task exceptions via capture_exception (default True). Default: True.
capture_task_lifecycle_eventsbool. Whether to emit lifecycle events of the task such as "started", "success", "failure" etc. (default True). Default: True.
propagate_contextbool. Whether to propagate PostHog context (distinct ID, session ID, tags, context options) from the producer to the worker via task headers (default True). Default: True.
task_filterOptional[Callable[[Optional[str], dict[str, Any]], bool]]. Optional callback (task_name, task_properties) -> bool expected to return False if a given task should not be tracked. Default: None.

Functions:

NameDescription
instrumentConnect Celery signal handlers to capture task events and exceptions. Call this after initializing the PostHog client and this integration.
shutdownDisconnect all signal handlers registered by instrument(), flush all pending events and cleanly shutdown the integration.
uninstrumentDisconnect Celery signal handlers and unregister exit cleanup.

Attributes:

NameTypeDescription
capture_exceptions
capture_task_lifecycle_events
client
propagate_context
task_filter

posthog.integrations.celery.PosthogCeleryIntegration.capture_exceptions

Python
capture_exceptions = capture_exceptions

posthog.integrations.celery.PosthogCeleryIntegration.capture_task_lifecycle_events

Python
capture_task_lifecycle_events = capture_task_lifecycle_events

posthog.integrations.celery.PosthogCeleryIntegration.client

Python
client = client

posthog.integrations.celery.PosthogCeleryIntegration.instrument

Python
instrument() -> None

Connect Celery signal handlers to capture task events and exceptions. Call this after initializing the PostHog client and this integration.

If Celery runs on a single host, reinstrumenting in worker children is not strictly necessary because the PostHog client and this integration are fork-safe. If Celery workers run across multiple hosts, each worker process must initialize PostHog, this integration, and call instrument(). Celery provides worker_process_init signal to help with this.

posthog.integrations.celery.PosthogCeleryIntegration.propagate_context

Python
propagate_context = propagate_context

posthog.integrations.celery.PosthogCeleryIntegration.shutdown

Python
shutdown() -> None

Disconnect all signal handlers registered by instrument(), flush all pending events and cleanly shutdown the integration.

shutdown() is also registered on worker_process_shutdown and atexit signals, but there is no guarantee those will always be called, so we strongly recommend calling it manually when the integration is no longer needed to avoid data loss.

posthog.integrations.celery.PosthogCeleryIntegration.task_filter

Python
task_filter = task_filter

posthog.integrations.celery.PosthogCeleryIntegration.uninstrument

Python
uninstrument() -> None

Disconnect Celery signal handlers and unregister exit cleanup.

Do not use directly, call shutdown() instead.

posthog.request.set_socket_options

Python
set_socket_options(socket_options: Optional[SocketOptions]) -> None

Configure socket options for all SDK HTTP connections.

Call this during initialization, before making API requests. Pass None to reset to the default socket behavior.

Parameters:

NameDescription
socket_optionsOptional[SocketOptions]. A list of (level, option, value) tuples accepted by urllib3/socket.setsockopt(), or None to reset defaults. Required.

Examples:

Python
import socket
from posthog import set_socket_options
set_socket_options([(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)])

posthog.request.enable_keep_alive

Python
enable_keep_alive() -> None

Enable TCP keepalive for SDK HTTP connections.

This helps prevent idle pooled connections from being dropped by network infrastructure. Call during initialization, before making API requests. Where the platform supports the corresponding socket options, it uses a 60 second idle time, a 60 second probe interval and 3 probes before timeout. Unsupported settings keep their system defaults.

posthog.request.disable_connection_reuse

Python
disable_connection_reuse() -> None

Disable HTTP connection reuse for SDK requests.

Each request will create a fresh connection. This can avoid issues with environments that terminate pooled connections, but adds per-request overhead. Call during initialization, before making API requests.

AsyncClient

Needs the async extra, posthog[async].

AsyncClient(...)

Python
AsyncClient(project_api_key: str, host: Optional[str] = None, *, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error=None, flush_at: int = 100, flush_interval: float = 5.0, max_retries: int = 3, timeout: float = 15, thread: int = 1, disabled: bool = False, disable_geoip: bool = True, is_server: bool = True, historical_migration: bool = False, super_properties: Optional[dict[str, Any]] = None, super_options: Optional[dict[str, Any]] = None, before_send=None, log_captured_exceptions: bool = False, project_root: Optional[str] = None, capture_exception_code_variables: bool = False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: Optional[list[str]] = None, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_PROPERTIES_SIZE, privacy_mode: bool = False, enable_full_ai_capture: bool = False, capture_trace_context: bool = False, secret_key: Optional[str] = None, personal_api_key: Optional[str] = None, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries: int = 1, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None) -> None

Create an async PostHog client. Import it as AsyncPosthog from posthog.

Keep one client for your app's lifetime on one event loop. Open it with async with AsyncPosthog(...), or call await shutdown() on teardown.

Know what to await

Queue methods write to memory and return right away. Network reads and lifecycle calls are coroutines.

CallMethodsReach for it when
Don't awaitcapture, capture_ai, set, set_once, group_identify, alias, capture_exceptionQueueing events on the request path without waiting on HTTP
awaitcapture_immediate, capture_ai_immediateA handler must confirm the upload attempt finished before returning
awaitevaluate_flags, get_remote_config_payload, emails.send, emails.get, flush, shutdown, joinEvaluating flags, sending emails, or draining queues on the event loop

The differences from Client

Shared constructor options behave the same as on Client(...), with these differences:

  • Remote flags only. secret_key authenticates get_remote_config_payload() and emails. AsyncPosthog doesn't poll flag definitions locally, so enable_local_evaluation, poll_interval, flag_definition_cache_provider, and flag_fallback_cache_url aren't accepted.
  • Async callbacks. before_send and on_error accept regular functions or async def coroutines.
  • Shared contexts. AsyncPosthog has no context methods. Open a context with posthog.new_context(), posthog.scoped(), or PosthogASGIMiddleware, then call posthog.identify_context() and posthog.tag() inside it.
  • Client-only options and methods. sync_mode, start_span(), metrics, traces, enable_exception_autocapture, enable_exception_autocapture_rate_limiting, and the exception_autocapture_* rate-limit options live on sync Posthog only and raise TypeError if passed here.

AsyncClient.capture

Python
capture(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Queue an event without blocking for network delivery.

Don't await this method. Call await capture_immediate() to wait for delivery, or see Client.capture for parameter rules.

AsyncClient.capture_immediate

Python
async capture_immediate(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture one event and wait until its delivery attempt completes.

AsyncClient.set

Python
set(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Queue a $set event to overwrite person properties.

Don't await this method, which uses identify_context() when distinct_id is omitted and folds active tags into $set. Without a distinct ID (explicit or from identify_context()), it sends nothing and returns None.

AsyncClient.set_once

Python
set_once(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Queue a $set_once event to set person properties only when unset.

Don't await this method. It follows the same context and tag rules as set() without overwriting existing values.

AsyncClient.alias

Python
alias(previous_id: ID_TYPES, distinct_id: Optional[str], timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[str] = None, disable_geoip: Optional[bool] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Queue a $create_alias event linking previous_id to distinct_id.

Don't await this method. Neither ID falls back to identify_context(), and you shouldn't alias users to a shared placeholder like "anonymous".

AsyncClient.capture_exception

Python
capture_exception(exception: Optional[ExceptionArg] = None, *, level: Optional[str] = None, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture an exception. This method never raises, including in debug mode.

level sets $exception_level and defaults to "error". An unknown value counts as unset. Reserved exception properties in properties, such as $exception_list and $exception_level, are ignored.

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, unless the event, a context tag or super_properties sets either one.

AsyncClient.emails

Python
emails: AsyncEmails

Send transactional email from PostHog templates or inline code, and read delivery status with get.

  • Requirements. Needs posthog[async] and a secret_key project secret API key with the transactional_email:write scope.
  • Routing. Sends go to app_host, or to the PostHog Cloud app host of host. For any other host, set app_host, or each call raises EmailError with code missing_app_host.
  • Retries and timeouts. Configured by email_request_timeout_seconds and email_request_max_retries. Emails lists the errors a send retries and the backoff.
  • Lifecycle. A disabled or shut-down client sends nothing. See posthog.emails for full setup.

Examples:

Python
await client.emails.send(
to="user@example.com",
template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
distinct_id="user_123",
)

AsyncClient.flush

Python
async flush(timeout_seconds: Optional[float] = 10) -> None

Drain queued analytics and AI events while keeping the client open.

Await this before a short-lived handler returns rather than calling shutdown() per request.

AsyncClient.evaluate_flags

Python
async evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations

Evaluate flags remotely without blocking the event loop.

The returned snapshot has synchronous in-memory accessors. Pass it to capture(flags=...) to attach the exact values used for branching. This client does not evaluate flags locally, so the snapshot's unresolved_flags is always empty.

AsyncClient.group_identify

Python
group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[Union[str, UUID]] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Queue a $groupidentify event to update group properties.

Don't await this method, which requires the Group Analytics add-on. Pass name in properties for the UI display name, and pass groups on capture() to link events.

AsyncClient.shutdown

Python
async shutdown() -> None

Flush queued events, stop async workers, and close HTTP transports.

Await this once at app teardown, or use async with AsyncPosthog(...). Don't reuse the client afterward.

AsyncClient.join

Python
async join() -> None

Alias for await shutdown().

AsyncClient.capture_ai

Python
capture_ai(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Queue an AI event for the AI capture endpoint without blocking.

Takes the same arguments and returns the same value as capture(). The event uses a separate queue with a larger per-event size cap. The payload is sent as given, with one exception: an event over capture_ai_max_event_bytes is sent without $ai_input, $ai_output, $ai_output_choices, $ai_input_state, $ai_output_state and $ai_tools, and with $ai_content_removal_reason="event_too_large" and $ai_event_bytes_before_removal added. It is dropped with an error log if it is still too large.

AsyncClient.capture_ai_immediate

Python
async capture_ai_immediate(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture one AI event and wait until its delivery attempt completes.

Uses the AI capture endpoint and the capture_ai_* settings.

AsyncClient.get_remote_config_payload

Python
async get_remote_config_payload(key: str) -> Optional[Any]

Fetch and decrypt a remote-config payload without blocking the loop.

Module functions

posthog.new_context

Python
new_context(fresh: bool = False, capture_exceptions: Optional[bool] = None, client: Optional[Client] = None)

Create a new context scope that will be active for the duration of the with block.

Contexts store shared identity, session ID, options, and tags in contextvars:

  • Scope required. identify_context(), tag(), and set_context_*() silently do nothing outside new_context() or @scoped().
  • Propagation. State carries across function calls and await automatically. New threads start with an empty context.
  • Inheritance. Child contexts inherit parent values without mutating the parent. Pass fresh=True at request or job boundaries to clear inherited state.
  • Precedence. Explicit arguments on capture() override context state, and context state overrides super_properties.

Parameters:

NameDescription
freshbool. Whether to start with a fresh context (default: False). Default: False.
capture_exceptionsOptional[bool]. Whether to capture uncaught exceptions escaping the with block. If omitted, defaults to the relevant client's exception autocapture setting. Default: None.
clientOptional[Client]. Optional Posthog client instance to use for this context (default: None). Default: None.

Examples:

Python
from posthog import new_context, tag, capture
with new_context():
tag("request_id", "123")
capture("event_name", properties={"property": "value"})

posthog.scoped

Python
scoped(fresh=False, capture_exceptions: Optional[bool] = None)

Decorator that creates a new context for the function.

Works on both sync and async def functions. Put scoped closest to the function when stacking decorators.

Parameters:

NameDescription
freshWhether to start with a fresh context (default: False). Default: False.
capture_exceptionsOptional[bool]. Whether to capture and track exceptions with posthog error tracking. If omitted, defaults to the global exception autocapture setting. Default: None.

Examples:

Python
from posthog import scoped, tag, capture
@scoped()
def process_payment(payment_id):
tag("payment_id", payment_id)
capture("payment_started")

posthog.set_context_session

Python
set_context_session(session_id: str)

Set the session ID for the current context.

Session IDs must be valid UUIDv7 strings. Forward PostHog JS's X-POSTHOG-SESSION-ID header here to link backend events to Session Replay.

Call this inside new_context() or @scoped(). Calls outside a context do nothing.

Parameters:

NameDescription
session_idstr. The session ID to associate with the current context and its children. Required.

Examples:

Python
from posthog import new_context, set_context_session
with new_context():
set_context_session("session_123")

posthog.set_context_device_id

Python
set_context_device_id(device_id: str)

Set the device ID for the current context, associating all feature flag requests in this or child contexts with the given device ID.

Call this inside new_context() or @scoped(). Calls outside a context do nothing.

Parameters:

NameDescription
device_idstr. The device ID to associate with the current context and its children. Required.

Examples:

Python
from posthog import new_context, set_context_device_id
with new_context():
set_context_device_id("device_123")

posthog.identify_context

Python
identify_context(distinct_id: str)

Identify the current context with a distinct ID.

Call this inside new_context() or @scoped(). Calls outside a context do nothing.

Parameters:

NameDescription
distinct_idstr. The distinct ID to associate with the current context and its children. Required.

Examples:

Python
from posthog import new_context, identify_context
with new_context():
identify_context("user_123")

posthog.set_capture_exception_code_variables_context

Python
set_capture_exception_code_variables_context(enabled: bool)

Override code-variable capture for exceptions in the current context.

Parameters:

NameDescription
enabledbool. Whether exceptions captured in this context should include local variable values from stack frames. Required.

posthog.set_code_variables_mask_patterns_context

Python
set_code_variables_mask_patterns_context(mask_patterns: list[str])

Override code-variable mask patterns for exceptions in the current context.

Parameters:

NameDescription
mask_patternslist[str]. Variable-name patterns whose values should be replaced with *** when code variables are captured. Required.

posthog.set_code_variables_ignore_patterns_context

Python
set_code_variables_ignore_patterns_context(ignore_patterns: list[str])

Override code-variable ignore patterns for exceptions in the current context.

Parameters:

NameDescription
ignore_patternslist[str]. Variable-name patterns that should be omitted entirely when code variables are captured. Required.

posthog.set_code_variables_mask_url_credentials_context

Python
set_code_variables_mask_url_credentials_context(enabled: bool)

Whether to scrub credentials embedded in URLs/DSNs (e.g. user:pass@host) from captured code variables for the current context.

posthog.set_code_variables_detect_secrets_context

Python
set_code_variables_detect_secrets_context(enabled: bool)

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.

posthog.tag

Python
tag(name: str, value: Any)

Add a tag to the current context.

Call this inside new_context() or @scoped(). Calls outside a context do nothing.

Parameters:

NameDescription
namestr. The tag key. Required.
valueAny. The tag value. Required.

Examples:

Python
from posthog import new_context, tag
with new_context():
tag("plan", "pro")

posthog.get_tags

Python
get_tags() -> Dict[str, Any]

Get all tags from the current context.

Returns:

TypeDescription
Dict[str, Any]Dict of all tags in the current context

posthog.set_context_option

Python
set_context_option(key: str, value: Any) -> None

Set a capture option for every event captured within the current context.

Context options fill options an event leaves unset, before before_send runs, so the hook sees them. They override super_options. An event's own options override them, and before_send can change them. They never set process_person_profile on identify-style events, such as $identify or $set, whose distinct ID the SDK did not generate: those default it to True.

Parameters:

NameDescription
keystr. The option name, such as "process_person_profile". Required.
valueAny. The option value, sent as given. Required.

Examples:

Python
from posthog import new_context, set_context_option
with new_context():
set_context_option("process_person_profile", False)

posthog.get_context_options

Python
get_context_options() -> Dict[str, Any]

Get all capture options from the current context.

Returns:

TypeDescription
Dict[str, Any]Dict of all capture options in the current context

posthog.capture

Python
capture(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture anything a user does within your system.

Parameters:

NameDescription
eventstr. The event name to specify the event. Required.
**kwargsUnpack[OptionalCaptureArgs]. Optional arguments including: distinct_id: Unique identifier for the user properties: Dict of event properties timestamp: When the event occurred. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. uuid: Unique identifier for this event. If omitted, one is generated and returned. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID. groups: Dict of group types and IDs flags: A FeatureFlagEvaluations snapshot from evaluate_flags(). The exact values from the snapshot are attached with no extra /flags request. send_feature_flags: Deprecated. Prefer flags=... from evaluate_flags(). When truthy, evaluates flags during capture and attaches them to the event. disable_geoip: Whether to disable GeoIP lookup. Default: {}.
Details

Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up. A capture call requires an event name to specify the event. We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on. Capture takes a number of optional arguments, which are defined by the OptionalCaptureArgs type.

Examples:

Python
# Context and capture usage
from posthog import new_context, identify_context, tag, capture
# Enter a new context (e.g. a request/response cycle, an instance of a background job, etc)
with new_context():
# Associate this context with some user, by distinct_id
identify_context('some user')
# Capture an event, associated with the context-level distinct ID ('some user')
capture('movie started')
# Capture an event associated with some other user (overriding the context-level distinct ID)
capture('movie joined', distinct_id='some-other-user')
# Capture an event with some properties
capture('movie played', properties={'movie_id': '123', 'category': 'romcom'})
# Capture an event with some properties
capture('purchase', properties={'product_id': '123', 'category': 'romcom'})
# Capture an event with some associated group
capture('purchase', groups={'company': 'id:5'})
# Adding a tag to the current context will cause it to appear on all subsequent events
tag('some-tag', 'some-value')
capture('another-event') # Will be captured with `'some-tag': 'some-value'` in the properties dict
Python
# Set event properties
from posthog import capture
capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)

posthog.capture_ai

Python
capture_ai(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

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 delivered on an isolated queue 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, with one exception: an event over capture_ai_max_event_bytes is sent without $ai_input, $ai_output, $ai_output_choices, $ai_input_state, $ai_output_state and $ai_tools, and with $ai_content_removal_reason="event_too_large" and $ai_event_bytes_before_removal added. It is dropped with an error log if it is still too large.

Parameters:

NameDescription
eventstr. The event name, normally one of the $ai_* event names. Required.
**kwargsUnpack[OptionalCaptureArgs]. Same optional arguments as capture(). Default: {}.

Examples:

Python
from posthog import capture_ai
uuid = capture_ai(
"$ai_generation",
distinct_id="user_123",
properties={"$ai_model": "gpt-5"},
)

posthog.set

Python
set(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Set properties on a user record.

Parameters:

NameDescription
**kwargsUnpack[OptionalSetArgs]. Optional arguments including: distinct_id: Unique identifier for the user. Falls back to the context distinct ID; if none exists, this call does nothing. properties: Dict of person properties to set. timestamp: When the properties were set. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. uuid: Unique identifier for this operation. If omitted, one is generated and returned. 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: Whether to disable GeoIP lookup. Default: {}.
Details

This will overwrite previous people property values. Generally operates similar to capture, with distinct_id being an optional argument, defaulting to the current context's distinct ID. If there is no context-level distinct ID, and no override distinct_id is passed, this function will do nothing. Context tags are folded into $set properties, so tagging the current context and then calling set will cause those tags to be set on the user (unlike capture, which causes them to just be set on the event).

Examples:

Python
# Set person properties
from posthog import set
set(distinct_id='distinct_id', properties={'name': 'Max Hedgehog'})

posthog.set_once

Python
set_once(**kwargs: Unpack[OptionalSetArgs]) -> Optional[str]

Set properties on a user record, only if they do not yet exist.

Parameters:

NameDescription
**kwargsUnpack[OptionalSetArgs]. Optional arguments including: distinct_id: Unique identifier for the user. Falls back to the context distinct ID; if none exists, this call does nothing. properties: Dict of person properties to set only once. timestamp: When the properties were set. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. uuid: Unique identifier for this operation. If omitted, one is generated and returned. 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: Whether to disable GeoIP lookup. Default: {}.
Details

This will not overwrite previous people property values, unlike set. Otherwise, operates in an identical manner to set.

Examples:

Python
# Set property once
from posthog import set_once
set_once(distinct_id='distinct_id', properties={'initial_url': '/blog'})

posthog.group_identify

Python
group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime.datetime, str]] = None, uuid: Optional[str] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Set properties on a group.

Parameters:

NameDescription
group_typestr. Type of your group. Required - the call is dropped with a warning if it is missing or empty. Required.
group_keystr. Unique identifier of the group. Required - the call is dropped with a warning if it is missing or empty. Required.
propertiesOptional[Dict[str, Any]]. Properties to set on the group. Default: None.
timestampOptional[Union[datetime, str]]. Optional timestamp for the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. Default: None.
uuidOptional[str]. Optional UUID for the event. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
distinct_idOptional[ID_TYPES]. Optional distinct ID of the user performing the action. Default: None.
optionsOptional[Dict[str, Any]]. Optional capture options for the event, sent as given. process_person_profile is True unless this call sets it. Default: None.

Examples:

Python
# Group identify
from posthog import group_identify
group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})

posthog.alias

Python
alias(previous_id: ID_TYPES, distinct_id: str, timestamp: Optional[Union[datetime.datetime, str]] = None, uuid: Optional[str] = None, disable_geoip: Optional[bool] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str]

Associate user behaviour before and after they e.g. register, login, or perform some other identifying action.

Parameters:

NameDescription
previous_idID_TYPES. The unique ID of the user before. Required.
distinct_idstr. The current unique id. Required.
timestampOptional[Union[datetime, str]]. Optional timestamp for the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. Default: None.
uuidOptional[str]. Optional UUID for the event. Default: None.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
optionsOptional[Dict[str, Any]]. Optional capture options for the event, sent as given. process_person_profile is True unless this call sets it. Default: None.
Details

To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?". Particularly useful for associating user behaviour before and after they e.g. register, login, or perform some other identifying action.

Examples:

Python
# Alias user
from posthog import alias
alias(previous_id='distinct_id', distinct_id='alias_id')

posthog.capture_exception

Python
capture_exception(exception: Optional[ExceptionArg] = None, *, level: Optional[str] = None, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str]

Capture exceptions that happen in your code.

Parameters:

NameDescription
exceptionOptional[ExceptionArg]. The exception to capture. If not provided, the current exception is captured via sys.exc_info(). Default: None.
levelOptional[str]. The $exception_level, such as "warning" or "fatal". Defaults to "error". An unknown value counts as unset. Default: None.
**kwargsUnpack[OptionalCaptureArgs]. Optional capture arguments including distinct_id, properties, timestamp, uuid, groups, flags, send_feature_flags, disable_geoip, and options. Reserved exception properties in properties, such as $exception_list and $exception_level, are ignored. Default: {}.
Details

Capture exception is idempotent - if it is called twice with the same exception instance, only a occurrence will be tracked in posthog. This is because, generally, contexts will cause exceptions to be captured automatically. However, to ensure you track an exception, if you catch and do not re-raise it, capturing it manually is recommended, unless you are certain it will have crossed a context boundary (e.g. by existing a with posthog.new_context(): block already). If the passed exception was raised and caught, the captured stack trace will consist of every frame between where the exception was raised and the point at which it is captured (the "traceback"). If the passed exception was never raised, e.g. if you call posthog.capture_exception(ValueError("Some Error")), the stack trace captured will be the full stack trace at the moment the exception was captured. Note that heavy use of contexts will lead to truncated stack traces, as the exception will be captured by the context entered most recently, which may not be the point you catch the exception for the final time in your code. It's recommended to use contexts sparingly, for this reason. capture_exception takes the same set of optional arguments as capture.

Examples:

Python
# Capture exception
from posthog import capture_exception
try:
risky_operation()
except Exception as e:
capture_exception(e)

posthog.feature_enabled

Python
feature_enabled(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[bool]

Use feature flags to enable or disable features for users.

feature_enabled is deprecated and will be removed in a future major version. Use posthog.evaluate_flags(distinct_id, ...) and call flags.is_enabled(key) instead. This consolidates flag evaluation into a single /flags request per incoming request.

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The user's distinct ID. Required.
groupsOptional[Mapping[str, Union[str, int]]]. Groups mapping. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
send_feature_flag_eventsbool. Whether to send feature flag events. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.
Details

You can call posthog.load_feature_flags() before to make sure you're not doing unexpected requests.

Examples:

Python
# 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')

posthog.get_feature_flag

Python
get_feature_flag(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FlagValue]

Get feature flag variant for users. Used with experiments.

get_feature_flag is deprecated and will be removed in a future major version. Use posthog.evaluate_flags(distinct_id, ...) and call flags.get_flag(key) instead. This consolidates flag evaluation into a single /flags request per incoming request.

Parameters:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The user's distinct ID. Required.
groupsOptional[Mapping[str, Union[str, int]]]. Groups mapping from group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties in format { group_type_name: { group_properties } }. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
send_feature_flag_eventsbool. Whether to send feature flag events. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.
Details

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}}.

Examples:

Python
# 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')

posthog.get_all_flags

Python
get_all_flags(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None) -> Optional[dict[str, FlagValue]]

Get all flags for a given user.

Parameters:

NameDescription
distinct_idID_TYPES. The user's distinct ID. Required.
groupsOptional[Mapping[str, Union[str, int]]]. Groups mapping. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.
flag_keys_to_evaluateOptional[list[str]]. Optional list of flag keys to evaluate (evaluates all if None). Default: None.
Details

Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.

Examples:

Python
# All flags for user
from posthog import get_all_flags
get_all_flags('distinct_id_of_your_user')

posthog.get_feature_flag_result

Python
get_feature_flag_result(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FeatureFlagResult]

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:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The user's distinct ID. Required.
groupsOptional[Mapping[str, Union[str, int]]]. Mapping of group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties to use for evaluation. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties keyed by group type. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
send_feature_flag_eventsbool. Whether to send a $feature_flag_called event. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.

Example:

Python
result = posthog.get_feature_flag_result('beta-feature', 'distinct_id')
if result and result.enabled:
# Use the variant and payload
print(f"Variant: {result.variant}")
print(f"Payload: {result.payload}")

posthog.get_feature_flag_payload

Python
get_feature_flag_payload(key: str, distinct_id: ID_TYPES, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[object]

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:

NameDescription
keystr. The feature flag key. Required.
distinct_idID_TYPES. The user's distinct ID. Required.
match_valueOptional[FlagValue]. Optional flag value to use when selecting a payload. Default: None.
groupsOptional[Mapping[str, Union[str, int]]]. Mapping of group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties to use for evaluation. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties keyed by group type. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
send_feature_flag_eventsbool. Whether to send a $feature_flag_called event. Default: True.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.

Returns:

TypeDescription
Optional[object]The payload associated with the matched feature flag value, or None. This function returns the payload only, not the FeatureFlagResult wrapper used internally to compute it.

posthog.get_remote_config_payload

Python
get_remote_config_payload(key: str)

Get the payload for a remote config feature flag.

Parameters:

NameDescription
keystr. The key of the feature flag. Required.

Returns:

TypeDescription
  • | The payload associated with the feature flag. If payload is encrypted, the return value will be decrypted
Note

Requires secret_key to be set for authentication

posthog.get_all_flags_and_payloads

Python
get_all_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None) -> FlagsAndPayloads

Get all feature flag values and payloads for a user.

Parameters:

NameDescription
distinct_idID_TYPES. The user's distinct ID. Required.
groupsOptional[Mapping[str, Union[str, int]]]. Mapping of group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties to use for evaluation. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties keyed by group type. Default: None.
only_evaluate_locallybool. Whether to evaluate only locally. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
device_idOptional[str]. Optional device ID override for experience-continuity flags. Default: None.
flag_keys_to_evaluateOptional[list[str]]. Optional list of flag keys to evaluate. Evaluates all flags when omitted. Default: None.

Returns:

TypeDescription
FlagsAndPayloadsA dict with featureFlags and featureFlagPayloads entries.

posthog.evaluate_flags

Python
evaluate_flags(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations

Evaluate all feature flags for a user in a single call and return a FeatureFlagEvaluations snapshot. Branch on .is_enabled() / .get_flag() and pass the same snapshot to 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.

Parameters:

NameDescription
distinct_idOptional[ID_TYPES]. The user's distinct ID. If None, falls back to the context distinct_id. If still unresolvable, returns an empty snapshot. Default: None.
groupsOptional[Mapping[str, Union[str, int]]]. Mapping of group type to group key. Default: None.
person_propertiesOptional[Dict[str, Any]]. Person properties to use for evaluation. Default: None.
group_propertiesOptional[Dict[str, Dict[str, Any]]]. Group properties keyed by group type. Default: None.
only_evaluate_locallybool. If True, never fall back to remote evaluation and omit flags that cannot be evaluated locally. The snapshot's unresolved_flags lists them with a reason. Default: False.
disable_geoipOptional[bool]. Whether to disable GeoIP lookup. Default: None.
flag_keysOptional[list[str]]. Optional list that scopes local evaluation, the underlying /flags request, and the returned snapshot. When omitted or None, 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 per evaluate_flags call unless only_evaluate_locally is True. If the server also does not know the key, it is omitted from the snapshot. Default: None.
device_idOptional[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. Default: None.

Examples:

Python
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)

posthog.feature_flag_definitions

Python
feature_flag_definitions()

Returns loaded feature flags.

Details

Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.

Examples:

Python
from posthog import feature_flag_definitions
definitions = feature_flag_definitions()

posthog.get_feature_flag_evaluation_runtime

Python
get_feature_flag_evaluation_runtime(key: str) -> Optional[FeatureFlagEvaluationRuntime]

Return where a locally loaded feature flag is meant to be evaluated.

Details

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.

Examples:

Python
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_evaluation_runtime
runtime = get_feature_flag_evaluation_runtime("my-flag")

posthog.get_feature_flag_keys_by_evaluation_runtime

Python
get_feature_flag_keys_by_evaluation_runtime(evaluation_runtime: Union[FeatureFlagEvaluationRuntime, str]) -> list[str]

Return the keys of locally loaded flags that a runtime can evaluate.

Details

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.

Examples:

Python
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_keys_by_evaluation_runtime
client_keys = get_feature_flag_keys_by_evaluation_runtime(FeatureFlagEvaluationRuntime.CLIENT)

posthog.load_feature_flags

Python
load_feature_flags()

Load feature flag definitions from PostHog.

Examples:

Python
from posthog import load_feature_flags
load_feature_flags()

posthog.flush

Python
flush(timeout_seconds: Optional[float] = 10) -> None

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:

NameDescription
timeout_secondsOptional[float]. Seconds to wait for event queues to drain, shared across event lanes. Defaults to 10 seconds. Pass None to 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's timeout in seconds, so this is not a strict wall-clock limit for the whole call. With None, a retriable span failure is left for a later flush rather than retried within this call. Default: 10.

Examples:

Python
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)

posthog.join

Python
join() -> None

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.

Examples:

Python
from posthog import join
join()

posthog.start_span

Python
start_span(name: str, *, kind: Optional[str] = None, attributes: Optional[Mapping[str, Any]] = None, parent: Union[Span, str, None] = None, tracestate: Optional[str] = None, start_time: Union[datetime.datetime, float, None] = None) -> Span

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:

NameDescription
namestr. A low-cardinality operation name, e.g. GET /users/:id. Variable values belong in attributes, not the name. Required.
kindOptional[str]. internal (default), server, client, producer or consumer. Default: None.
attributesOptional[Mapping[str, Any]]. Initial attributes. Default: None.
parentUnion[Span, str, None]. A span handle, or an inbound W3C traceparent header value to continue a remote trace. Defaults to the active span. Default: None.
tracestateOptional[str]. The inbound tracestate header accompanying a traceparent string parent; preserved and propagated. Default: None.
start_timeUnion[datetime, float, None]. A datetime or epoch seconds, to backdate the span. Default: None.

Examples:

Python
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()}

posthog.get_active_span

Python
get_active_span() -> Optional[Span]

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.

Examples:

Python
span = posthog.get_active_span()
if span is not None:
headers["traceparent"] = span.traceparent()

posthog.shutdown

Python
shutdown() -> None

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.

Examples:

Python
from posthog import shutdown
shutdown()

posthog.setup

Python
setup() -> Client

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:

TypeDescription
ClientThe 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.

Types

OptionalCaptureArgs

Bases: TypedDict

Optional arguments for the capture method.

Parameters:

NameDescription
distinct_idUnique identifier for the person associated with this event. If not set, the context distinct_id is used, if available, otherwise a UUID is generated, and the event is marked as personless. Setting context-level distinct_id's is recommended.
propertiesDictionary of properties to track with the event
timestampWhen the event occurred (defaults to current time). UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
uuidUnique identifier for this specific event. If not provided, one is generated. The event UUID is returned, so you can correlate it with actions in your app (like showing users an error ID if you capture an exception). If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID.
groupsGroup identifiers to associate with this event (format: {group_type: group_key})
flagsA FeatureFlagEvaluations snapshot from evaluate_flags(). The exact flag values from the snapshot are attached to the event with no additional network call — prefer this over send_feature_flags.
send_feature_flagsDeprecated — prefer flags with a FeatureFlagEvaluations snapshot. Whether to include currently active feature flags in the event properties. Can be a boolean or a SendFeatureFlagsOptions object. Defaults to False. Fires a hidden /flags request on capture and may return different values than the ones the code branched on.
disable_geoipWhether to disable GeoIP lookup for this event. Defaults to False.
optionsCapture options for this event, such as {"process_person_profile": False}. Sent as given, for PostHog to validate. An option wins over its legacy $ property, such as $process_person_profile. A value that is not a dict is logged and ignored. An identify-style event, such as $identify or $set, gets process_person_profile: True when this call leaves it unset, unless the SDK generated its distinct ID.

Attributes:

NameTypeDescription
disable_geoipNotRequired[Optional[bool]]
distinct_idNotRequired[Optional[ID_TYPES]]
flagsNotRequired[Optional[FeatureFlagEvaluations]]
groupsNotRequired[Optional[Dict[str, str]]]
optionsNotRequired[Optional[Dict[str, Any]]]
propertiesNotRequired[Optional[Dict[str, Any]]]
send_feature_flagsNotRequired[Optional[Union[bool, SendFeatureFlagsOptions]]]
timestampNotRequired[Optional[Union[datetime, str]]]
uuidNotRequired[Optional[Union[str, UUID]]]

posthog.args.OptionalCaptureArgs.disable_geoip

Python
disable_geoip: NotRequired[Optional[bool]]

posthog.args.OptionalCaptureArgs.distinct_id

Python
distinct_id: NotRequired[Optional[ID_TYPES]]

posthog.args.OptionalCaptureArgs.flags

Python
flags: NotRequired[Optional[FeatureFlagEvaluations]]

posthog.args.OptionalCaptureArgs.groups

Python
groups: NotRequired[Optional[Dict[str, str]]]

posthog.args.OptionalCaptureArgs.options

Python
options: NotRequired[Optional[Dict[str, Any]]]

posthog.args.OptionalCaptureArgs.properties

Python
properties: NotRequired[Optional[Dict[str, Any]]]

posthog.args.OptionalCaptureArgs.send_feature_flags

Python
send_feature_flags: NotRequired[Optional[Union[bool, SendFeatureFlagsOptions]]]

posthog.args.OptionalCaptureArgs.timestamp

Python
timestamp: NotRequired[Optional[Union[datetime, str]]]

posthog.args.OptionalCaptureArgs.uuid

Python
uuid: NotRequired[Optional[Union[str, UUID]]]

FeatureFlagEvaluations

Python
FeatureFlagEvaluations(host: _FeatureFlagEvaluationsHost, distinct_id: str, flags: Dict[str, _EvaluatedFlagRecord], groups: Optional[Mapping[str, Union[str, int]]] = None, disable_geoip: Optional[bool] = None, request_id: Optional[str] = None, evaluated_at: Optional[int] = None, errors_while_computing: bool = False, quota_limited: bool = False, minimal_flag_called_events: bool = False, accessed: Optional[Set[str]] = None, unresolved_flags: Optional[Mapping[str, UnresolvedFlagReason]] = None) -> None

A point-in-time snapshot of feature flag evaluations for a single distinct_id.

Returned by Client.evaluate_flags — branch on is_enabled / get_flag and pass the same object to Client.capture via the flags option so the captured event carries the exact flag values the code branched on.

Python
flags = posthog.evaluate_flags(distinct_id, person_properties={"plan": "enterprise"})
if flags.is_enabled("new-dashboard"):
render_new_dashboard()
posthog.capture("page_viewed", distinct_id=distinct_id, flags=flags)

To narrow the set of flags that get attached to a captured event, use the in-memory helpers only and only_accessed. To narrow the set of flags requested from the server in the first place, pass flag_keys to Client.evaluate_flags.

Reading a flag sends $feature_flag_called, deduplicated as is_enabled describes. When the flag's config version 2 record is a complete experiment split (an experiment rule with a rule ID and a variant key), the read also sends $experiment_exposure. The SDK sends one exposure per distinct ID, groups, flag, rule and variant. send_feature_flag_events=False suppresses both events.

Functions:

NameDescription
get_flagReturn the flag value. Fires $feature_flag_called on first access.
get_flag_payloadReturn the payload associated with a flag.
is_enabledReturn whether the flag is enabled. Fires $feature_flag_called on the first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache.
onlyReturn a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. Selected failures retain private diagnostics but remain absent from values, keys and enrichment; their existing missing-value warning is unchanged.
only_accessedReturn a filtered copy containing only flags accessed via is_enabled or get_flag before this call.

Attributes:

NameTypeDescription
keysList[str]Return the flag keys that are part of this evaluation.
unresolved_flagsMapping[str, UnresolvedFlagReason]Return a read-only mapping of flag key to the reason local evaluation left it without a value.

Internal — instances are created by the SDK via Client.evaluate_flags().

posthog.feature_flag_evaluations.FeatureFlagEvaluations.get_flag

Python
get_flag(key: str, *, send_feature_flag_events: bool = True) -> Optional[FlagValue]

Return the flag value. Fires $feature_flag_called on first access.

Returns the variant string for multivariate flags, True for enabled flags without a variant, False for disabled flags, and None for flags that were not returned or whose remote record was marked failed by the server. An unreadable remote record retains its disabled (False) result.

Pass send_feature_flag_events=False to skip the event for this read, as with is_enabled.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.get_flag_payload

Python
get_flag_payload(key: str) -> Optional[Any]

Return the payload associated with a flag.

Does not count as an access for only_accessed and does not fire any event.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.is_enabled

Python
is_enabled(key: str, default_value: bool = False, *, send_feature_flag_events: bool = True) -> bool

Return whether the flag is enabled. Fires $feature_flag_called on the first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache.

Parameters:

NameDescription
keystr. The feature flag key. Required.
default_valuebool. Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, the server marked its record failed, or the evaluation itself came back empty (failed /flags request, quota limit, or no resolvable distinct_id). Defaults to False. Default: False.
send_feature_flag_eventsbool. Whether this read sends $feature_flag_called. When False, no event is sent and the dedupe cache is left alone, but the key still counts as accessed for only_accessed. Default: True.

A flag that has a value always wins over default_value, including a disabled flag, which returns False even when default_value=True.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.keys

Python
keys: List[str]

Return the flag keys that are part of this evaluation.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.only

Python
only(keys: List[str]) -> FeatureFlagEvaluations

Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. Selected failures retain private diagnostics but remain absent from values, keys and enrichment; their existing missing-value warning is unchanged.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.only_accessed

Python
only_accessed() -> FeatureFlagEvaluations

Return a filtered copy containing only flags accessed via is_enabled or get_flag before this call.

Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result. Accessed failures retain private diagnostics, not values or enrichment.

posthog.feature_flag_evaluations.FeatureFlagEvaluations.unresolved_flags

Python
unresolved_flags: Mapping[str, UnresolvedFlagReason]

Return a read-only mapping of flag key to the reason local evaluation left it without a value.

A flag is listed when it has a loaded local definition, was in the requested scope, was inconclusive locally, and no remote value filled the gap. Listed flags are not part of keys, and reading one reports the local_evaluation_inconclusive error instead of flag_missing. A server-marked failed fallback additionally reports evaluation_failed. Reading this mapping does not count as an access and does not fire any event. Snapshots returned by only and only_accessed, and by AsyncClient.evaluate_flags(), which evaluates only remotely, carry no entries.

FeatureFlagResult

Python
FeatureFlagResult(key: str, enabled: bool, variant: Optional[str], payload: Optional[Any], reason: Optional[str]) -> None

The result of calling a feature flag which includes the flag result, variant, and payload.

Attributes:

NameTypeDescription
keystrThe unique identifier of the feature flag.
enabledboolWhether the feature flag is enabled for the current context.
variantOptional[str]The variant value if the flag is enabled and has variants, None otherwise.
payloadOptional[Any]Additional data associated with the feature flag, if any.
reasonOptional[str]A description of why the flag was enabled or disabled, if available.

Functions:

NameDescription
from_flag_detailsCreate a FeatureFlagResult from a FeatureFlag object.
from_value_and_payloadCreates a FeatureFlagResult from a flag value and payload.
get_valueReturns the value of the flag. This is the variant if it exists, otherwise the enabled value. This is the value we report as $feature_flag_response in the $feature_flag_called event.

posthog.types.FeatureFlagResult.enabled

Python
enabled: bool

posthog.types.FeatureFlagResult.from_flag_details

Python
from_flag_details(details: Union[FeatureFlag, None], override_match_value: Optional[FlagValue] = None) -> FeatureFlagResult | None

Create a FeatureFlagResult from a FeatureFlag object.

Parameters:

NameDescription
detailsUnion[FeatureFlag, None]. The FeatureFlag object to convert. Required.
override_match_valueOptional[FlagValue]. If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. A server-marked failure returns None even when this override is provided. Default: None.

Returns:

TypeDescription
FeatureFlagResult | NoneFeatureFlagResult

posthog.types.FeatureFlagResult.from_value_and_payload

Python
from_value_and_payload(key: str, value: Union[FlagValue, None], payload: Any) -> Union[FeatureFlagResult, None]

Creates a FeatureFlagResult from a flag value and payload.

Parameters:

NameDescription
keystr. The unique identifier of the feature flag. Required.
valueUnion[FlagValue, None]. The value of the flag (string variant or boolean). Required.
payloadAny. Additional data associated with the feature flag. Required.

Returns:

TypeDescription
Union[FeatureFlagResult, None]Union[FeatureFlagResult, None]: A new FeatureFlagResult instance, or None if value is None.

posthog.types.FeatureFlagResult.get_value

Python
get_value() -> FlagValue

Returns the value of the flag. This is the variant if it exists, otherwise the enabled value. This is the value we report as $feature_flag_response in the $feature_flag_called event.

Returns:

NameTypeDescription
FlagValueFlagValueEither a string variant or boolean value representing the flag's state.

posthog.types.FeatureFlagResult.key

Python
key: str

posthog.types.FeatureFlagResult.payload

Python
payload: Optional[Any]

posthog.types.FeatureFlagResult.reason

Python
reason: Optional[str]

posthog.types.FeatureFlagResult.variant

Python
variant: Optional[str]

FeatureFlag

Python
FeatureFlag(key: str, enabled: bool, variant: Optional[str], reason: Optional[FlagReason], metadata: Union[FlagMetadata, LegacyFlagMetadata]) -> None

Detailed feature flag evaluation returned by the flags API.

enabled, variant and metadata.payload are the value rendered the way responses before /flags?v=4 carried it, which the legacy getters return.

Attributes:

NameTypeDescription
keystrFeature flag key.
enabledboolWhether the flag is enabled for the evaluated user or group.
variantOptional[str]Variant key for multivariate flags, otherwise None.
reasonOptional[FlagReason]Optional reason metadata explaining the result.
metadataUnion[FlagMetadata, LegacyFlagMetadata]Payload and other metadata returned by the API.

Functions:

NameDescription
from_jsonParse one flag record of a /flags response.
from_value_and_payloadBuild a flag from its value and payload. A string value is a variant, so the flag is enabled.
get_valueReturn the variant for a multivariate flag, otherwise whether the flag is enabled.

posthog.types.FeatureFlag.enabled

Python
enabled: bool

posthog.types.FeatureFlag.from_json

Python
from_json(resp: Any) -> FeatureFlag

Parse one flag record of a /flags response.

A record with a value member is a /flags?v=4 record. A record without one comes from an older server: its value is variant, or enabled when there is no variant, and its config version is 1.

posthog.types.FeatureFlag.from_value_and_payload

Python
from_value_and_payload(key: str, value: FlagValue, payload: Any) -> FeatureFlag

Build a flag from its value and payload. A string value is a variant, so the flag is enabled.

posthog.types.FeatureFlag.get_value

Python
get_value() -> FlagValue

Return the variant for a multivariate flag, otherwise whether the flag is enabled.

posthog.types.FeatureFlag.key

Python
key: str

posthog.types.FeatureFlag.metadata

Python
metadata: Union[FlagMetadata, LegacyFlagMetadata]

posthog.types.FeatureFlag.reason

Python
reason: Optional[FlagReason]

posthog.types.FeatureFlag.variant

Python
variant: Optional[str]

FlagsAndPayloads

Bases: TypedDict

Feature flag values and payloads keyed by feature flag key.

Attributes:

NameTypeDescription
featureFlagsOptional[dict[str, FlagValue]]Each flag's value, keyed by flag key.
featureFlagPayloadsOptional[dict[str, Any]]Each flag's payload, keyed by flag key.

posthog.types.FlagsAndPayloads.featureFlagPayloads

Python
featureFlagPayloads: Optional[dict[str, Any]]

posthog.types.FlagsAndPayloads.featureFlags

Python
featureFlags: Optional[dict[str, FlagValue]]

UnresolvedFlagReason

Bases: str, Enum

Why local evaluation left a flag without a value.

Reported by FeatureFlagEvaluations.unresolved_flags. Inheriting from str keeps the members directly comparable to their string values. When more than one cause applies, the first reason in the order below is reported:

ReasonCause
EXPERIENCE_CONTINUITYThe flag has experience continuity enabled, which local evaluation never resolves. Change the flag to fix it.
UNSUPPORTED_DEFINITIONThe flag uses something the local evaluator doesn't support, such as a static cohort, an unknown operator or filter type, a malformed value, a dependency with no loaded definition, or a circular dependency. Change the flag or upgrade the SDK to fix it.
UNRESOLVED_DEPENDENCYA flag this flag depends on has a loaded definition but was unresolved.
MISSING_CONTEXTThe call didn't pass a property, group property, or device ID the flag needs, or passed it in an unusable form. Pass it to fix it.

Attributes:

NameTypeDescription
EXPERIENCE_CONTINUITY
MISSING_CONTEXT
UNRESOLVED_DEPENDENCY
UNSUPPORTED_DEFINITION

posthog.types.UnresolvedFlagReason.EXPERIENCE_CONTINUITY

Python
EXPERIENCE_CONTINUITY = 'experience_continuity'

posthog.types.UnresolvedFlagReason.MISSING_CONTEXT

Python
MISSING_CONTEXT = 'missing_context'

posthog.types.UnresolvedFlagReason.UNRESOLVED_DEPENDENCY

Python
UNRESOLVED_DEPENDENCY = 'unresolved_dependency'

posthog.types.UnresolvedFlagReason.UNSUPPORTED_DEFINITION

Python
UNSUPPORTED_DEFINITION = 'unsupported_definition'

InconclusiveMatchError

Python
InconclusiveMatchError(*args, reason: Optional[UnresolvedFlagReason] = None)

Bases: Exception

Raised when local evaluation can't determine a flag's value. reason says why, as reported by FeatureFlagEvaluations.unresolved_flags.

Attributes:

NameTypeDescription
reasonUnresolvedFlagReasonWhy local evaluation couldn't resolve the flag.

posthog.feature_flags.InconclusiveMatchError.reason

Python
reason: UnresolvedFlagReason = UnresolvedFlagReason.UNSUPPORTED_DEFINITION

RequiresServerEvaluation

Python
RequiresServerEvaluation(*args, reason: Optional[UnresolvedFlagReason] = None)

Bases: Exception

Raised when feature flag evaluation requires server-side data that is not available locally (e.g., static cohorts).

This error should propagate immediately to trigger API fallback, unlike InconclusiveMatchError which allows trying other conditions.

Attributes:

NameTypeDescription
reasonUnresolvedFlagReasonWhy the flag needs server-side evaluation.

posthog.feature_flags.RequiresServerEvaluation.reason

Python
reason: UnresolvedFlagReason = UnresolvedFlagReason.UNSUPPORTED_DEFINITION

CaptureError

Python
CaptureError(status: int | str, message: str, *, endpoint: str, retry_after: Optional[float] = None, request_id: Optional[str] = None, attempts: Optional[int] = None, retry_exhausted: Optional[list[str]] = None, drops: Optional[Sequence[tuple[str, Optional[str]]]] = None, event_results: Optional[dict[str, CaptureEventResult]] = None)

Bases: APIError

A capture batch that was not fully delivered.

Passed to on_error with the batch. status is the HTTP status of the last attempt, or 0 when no response arrived (__cause__ holds the transport error). A 2xx status means the request succeeded but some events were dropped or ran out of retries.

event_results maps each event uuid to its last verdict from a 2xx response. Events missing from it never got a verdict, because every attempt that reached them failed as a whole request.

drops lists each event the server dropped on a 2xx response as a CaptureDroppedEvent.

Functions:

NameDescription
verdict_summaryCount the undelivered events by verdict and reason, for example drop/llm_events_over_quota=2, retry/not_persisted=1.

Attributes:

NameTypeDescription
attempts
drops
endpoint
event_results
message
request_id
retry_after
retry_exhausted
status

posthog.capture_send.CaptureError.attempts

Python
attempts = attempts

posthog.capture_send.CaptureError.drops

Python
drops = [(CaptureDroppedEvent(*drop)) for drop in (drops or [])]

posthog.capture_send.CaptureError.endpoint

Python
endpoint = endpoint

posthog.capture_send.CaptureError.event_results

Python
event_results = event_results or {}

posthog.capture_send.CaptureError.message

Python
message = message

posthog.capture_send.CaptureError.request_id

Python
request_id = request_id

posthog.capture_send.CaptureError.retry_after

Python
retry_after = retry_after

posthog.capture_send.CaptureError.retry_exhausted

Python
retry_exhausted = retry_exhausted or []

posthog.capture_send.CaptureError.status

Python
status = status

posthog.capture_send.CaptureError.verdict_summary

Python
verdict_summary() -> str

Count the undelivered events by verdict and reason, for example drop/llm_events_over_quota=2, retry/not_persisted=1.

Counts the events in drops and retry_exhausted: events the server dropped, and events still pending retry after the last 2xx response. A retry verdict followed by a failed request, for example a 503 on the last attempt, is not counted; event_results keeps it. Empty when no event is counted.

Span

A handle to a span.

Every method is safe to call on any handle, including after end() and on the inert handles returned when tracing is off, so calling code never branches on whether tracing is running. Entering a handle (with span:) makes it the active span for the block and ends it on exit, recording an Exception raised inside it. A BaseException that is not an Exception (GeneratorExit, CancelledError, KeyboardInterrupt) still ends the span but is not recorded as a failure.

Functions:

NameDescription
add_eventAdd a timestamped event to the span. Ignored after end().
endEnd the span and queue it for export. Idempotent.
record_exceptionRecord an exception as an exception event and mark the span error.
set_attributeSet one attribute on the span; last write wins. Ignored after end().
set_attributesSet several attributes at once; last write wins per key. Ignored after end().
set_statusSet the span status to "ok" or "error". Ignored after end().
traceparentThe W3C traceparent header value to propagate, or None.
tracestateThe W3C tracestate header value to propagate, or None.
update_nameRename the span, for a name only known after it started. Ignored after end().

posthog.tracing.span.Span.add_event

Python
add_event(name: str, attributes: Optional[Mapping[str, Any]] = None, timestamp: Union[datetime, float, None] = None) -> Span

Add a timestamped event to the span. Ignored after end().

timestamp defaults to now; it accepts a datetime, or seconds since the epoch as a float or int. Returns the span, so calls chain.

Examples:

Python
span.add_event("cache.miss", {"key": "user:42"})

posthog.tracing.span.Span.end

Python
end(end_time: Union[datetime, float, None] = None) -> None

End the span and queue it for export. Idempotent.

end_time defaults to now; it accepts a datetime, or seconds since the epoch as a float or int, and is never earlier than the start. Later calls, and later mutations, no-op. with span: ends the span on exit, so call this only for spans started manually.

Examples:

Python
span = posthog.start_span("job")
try:
run_job()
finally:
span.end()

posthog.tracing.span.Span.record_exception

Python
record_exception(exception: BaseException) -> Span

Record an exception as an exception event and mark the span error.

Ignored after end(). The event carries exception.type, exception.message and, for a raised exception, exception.stacktrace (its last max_attribute_value_length characters, so a chained traceback keeps the outermost exception and may lose its cause). Returns the span, so calls chain. Inside with span: a raised Exception is recorded automatically, so this is for exceptions that are caught and handled.

The stack trace contains file paths from your server. Remove exception.stacktrace in before_span_send to keep them in your process. The exception event uses one of the span's event slots. A span whose event slots are full keeps its error status and the exception message, but loses the exception type and stack trace.

Examples:

Python
try:
charge(card)
except PaymentError as e:
span.record_exception(e)

posthog.tracing.span.Span.set_attribute

Python
set_attribute(key: str, value: Any) -> Span

Set one attribute on the span; last write wins. Ignored after end().

Returns the span, so calls chain. Prefer primitive values: strings, booleans, integers and floats keep their type. Lists and mappings are sent as OTLP arrays and maps, but PostHog stores them as serialized strings. None removes the key; anything else is stringified.

Examples:

Python
span.set_attribute("http.status_code", 200).set_attribute("cache.hit", True)

posthog.tracing.span.Span.set_attributes

Python
set_attributes(attributes: Mapping[str, Any]) -> Span

Set several attributes at once; last write wins per key. Ignored after end().

Returns the span, so calls chain. Same encoding as set_attribute().

Examples:

Python
span.set_attributes({"db.system": "postgresql", "db.rows": 12})

posthog.tracing.span.Span.set_status

Python
set_status(code: str, message: Optional[str] = None) -> Span

Set the span status to "ok" or "error". Ignored after end().

Unset by default. Any other code is ignored. ok is final for the scoped form: an Exception raised inside with span: does not override it. Returns the span, so calls chain.

Examples:

Python
span.set_status("error", "upstream timed out")

posthog.tracing.span.Span.traceparent

Python
traceparent() -> Optional[str]

The W3C traceparent header value to propagate, or None.

posthog.tracing.span.Span.tracestate

Python
tracestate() -> Optional[str]

The W3C tracestate header value to propagate, or None.

posthog.tracing.span.Span.update_name

Python
update_name(name: str) -> Span

Rename the span, for a name only known after it started. Ignored after end().

Returns the span, so calls chain.

Examples:

Python
span = posthog.start_span("http.request")
span.update_name(f"{request.method} {route.pattern}")

Emails

Python
Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None, migrated_from: Optional[str] = None) -> None

Bases: _EmailsBase

Sends transactional email from PostHog email templates or from content in your code.

host is your PostHog app host. PostHog Cloud ingestion hosts map to the app host, so us.i.posthog.com sends to us.posthog.com. Any other host is used as given, so for a self-hosted PostHog pass its app URL, never a proxy that must not see the secret key. From SDK 8.0.2, a self-hosted PostHog must be from 2026-11-18 or later. Older PostHog versions answer every email call with a 404, which raises not_found.

Retries: a send retries up to max_retries times after a network error, a 409 idempotency_key_in_flight, a 429 other than quota_limited or upload_quota_exceeded, or a 503. It waits about 1 second, then 2, doubling to at most 30, or the server's Retry-After when that is longer. A Retry-After over 30 seconds raises at once. Every attempt sends the same idempotency key, so a retry never sends the email twice. An attachment upload also retries a 429, 500, 502, 503 or 504 from the file storage, and get retries like a send. Set max_retries=0 when a job runner already retries the send.

timeout is in seconds, per request. Pass session to send through your own requests.Session, for example a test double. migrated_from, such as "resend", tells PostHog which provider your sends came from.

Functions:

NameDescription
closeClose the HTTP connections this client opened. A session you passed in stays open.
getRead what happened to an email that send queued.
sendQueue one email, from a template in PostHog or from content in your code.

Attributes:

NameTypeDescription
disabled
host
max_retries
migrated_from
secret_key
timeout

posthog.emails.Emails.close

Python
close() -> None

Close the HTTP connections this client opened. A session you passed in stays open.

posthog.emails.Emails.disabled

Python
disabled = disabled

posthog.emails.Emails.get

Python
get(message_id: Union[str, UUID]) -> EmailStatus

Read what happened to an email that send queued.

Needs a secret_key with the transactional_email:read or transactional_email:write scope.

Parameters:

NameDescription
message_idUnion[str, UUID]. The id of the SendEmailResult that send returned. Required.

Returns:

TypeDescription
EmailStatusThe email's latest status, for 30 days after the send.

Raises:

TypeDescription
EmailErrorPostHog did not answer with a status. code is not_found for an unknown ID, an email older than 30 days, for a few seconds after the send, or from a self-hosted PostHog older than 2026-11-18. The client doesn't retry not_found, so right after a send, try again a few times with a short wait before you treat the email as missing.
ValueErrormessage_id is not a message ID.

Examples:

Python
result = emails.send(to="user@example.com", template_id="...")
status = emails.get(result.id)
if status.status == "bounced":
print(status.reason)

posthog.emails.Emails.host

Python
host = determine_app_host(host)

posthog.emails.Emails.max_retries

Python
max_retries = max_retries

posthog.emails.Emails.migrated_from

Python
migrated_from = migrated_from

posthog.emails.Emails.secret_key

Python
secret_key = secret_key.strip() if isinstance(secret_key, str) else None

posthog.emails.Emails.send

Python
send(**kwargs: Any) -> SendEmailResult

Queue one email, from a template in PostHog or from content in your code.

Pass exactly one form. The template form, from SDK 7.81.0, names a template made in PostHog with template_id. The code form, from SDK 7.84.0, names the email with template_key and passes subject and html, text or both: see CodeEmailArgs for each of its fields in full. Use SDK 8.0.2 or later, because earlier versions call /api/projects/@current/... paths, which PostHog is removing.

Parameters:

NameDescription
toRequired. One recipient email address.
template_idRequired in the template form. The UUID of a template made transactional in PostHog.
template_dataTemplate form. Values for the template's {{ variables.* }} placeholders. Values are encoded the way capture encodes properties.
template_keyRequired in the code form. Names the email, so its metrics, logs and status group under it.
subjectRequired in the code form. The subject line.
htmlCode form. The HTML body. Give html, text or both.
textCode form. The plain-text body. Without it, PostHog derives it from html.
from_Code form. A verified sender. The underscore avoids the from keyword.
reply_toCode form. One address or a list of addresses.
ccCode form, from SDK 7.91.0. One address or a list, at most 10.
bccCode form, from SDK 7.91.0. One address or a list, at most 10.
attachmentsCode form, from SDK 7.91.0. A list of EmailAttachment dicts, at most 10 files.
sensitiveCode form, from SDK 7.89.0. Marks an email that carries login links, reset tokens or codes.
trackingCode form, from SDK 7.89.0. True, False or an EmailTracking dict.
capture_engagementCode form. Deprecated, use tracking={"engagement": False}.
distinct_idThe recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address.
idempotency_key1 to 255 visible ASCII characters. A send with a key that PostHog has already accepted queues nothing and returns the first send's result. Without it, the client makes a key that covers its own retries. Pass a key derived from what the email is for, such as welcome:user_123, to cover retries outside this call, too. PostHog keeps a key for 7 days, so finish your own retries within 7 days of the first send.
max_retriesOverrides the client's maximum number of retries for this send. 0 turns retries off.

Returns:

TypeDescription
SendEmailResultThe queued email. A result means PostHog queued the email, not that it was delivered.

Raises:

TypeDescription
EmailErrorPostHog did not queue the email, or the client could not tell whether it did, after the retries that Emails describes. Branch on code. With attachments, code is too_many_attachments, message_too_large or invalid_attachment before any request, attachment_upload_failed when the storage refused an upload, and network_error with field naming the attachment when the storage didn't answer.
(TypeError, ValueError)An argument has the wrong type or format, the call passes both template_id and template_key or neither, or it passes a field its form doesn't take. Nothing is sent.

Examples:

Python
emails.send(
to="user@example.com",
template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
template_data={"name": "Ada"},
distinct_id="user_123",
idempotency_key="welcome:user_123",
)
emails.send(
to="user@example.com",
template_key="password-reset",
subject="Reset your password",
html=rendered_html,
distinct_id="user_123",
)

posthog.emails.Emails.timeout

Python
timeout = timeout

AsyncEmails

Python
AsyncEmails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, http_client: Any = None, migrated_from: Optional[str] = None) -> None

Bases: _EmailsBase

The async counterpart of Emails. Needs posthog[async].

Pass http_client to send through your own httpx.AsyncClient, for example one with an httpx.MockTransport in tests.

Functions:

NameDescription
acloseClose the HTTP connections this client opened. An http_client you passed in stays open.
getRead what happened to an email that send queued.
sendQueue one email, from a template in PostHog or from content in your code.

Attributes:

NameTypeDescription
disabled
host
max_retries
migrated_from
secret_key
timeout

posthog.emails.AsyncEmails.aclose

Python
async aclose() -> None

Close the HTTP connections this client opened. An http_client you passed in stays open.

posthog.emails.AsyncEmails.disabled

Python
disabled = disabled

posthog.emails.AsyncEmails.get

Python
async get(message_id: Union[str, UUID]) -> EmailStatus

Read what happened to an email that send queued.

Takes the same argument and raises the same errors as Emails.get.

posthog.emails.AsyncEmails.host

Python
host = determine_app_host(host)

posthog.emails.AsyncEmails.max_retries

Python
max_retries = max_retries

posthog.emails.AsyncEmails.migrated_from

Python
migrated_from = migrated_from

posthog.emails.AsyncEmails.secret_key

Python
secret_key = secret_key.strip() if isinstance(secret_key, str) else None

posthog.emails.AsyncEmails.send

Python
async send(**kwargs: Any) -> SendEmailResult

Queue one email, from a template in PostHog or from content in your code.

Takes the same arguments and raises the same errors as Emails.send.

Examples:

Python
await emails.send(
to="user@example.com",
template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
template_data={"name": "Ada"},
distinct_id="user_123",
)

posthog.emails.AsyncEmails.timeout

Python
timeout = timeout

EmailError

Python
EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None) -> None

Bases: Exception

PostHog did not queue the email, or the client could not tell whether it did.

Branch on code, PostHog's stable error code, or on name, a coarse category of the failure. The message never contains the secret key or the request body.

Codes a setup usually hits are missing_secret_key, missing_app_host, authentication_failed or not_authenticated (401), permission_denied (403), not_found (404, also from a self-hosted PostHog older than 2026-11-18), client_disabled and client_closed. A network_error or a 503 doesn't mean the email failed, because PostHog can still have queued it, unless field names an attachment. Retry with the same idempotency_key you passed to send. The key the client makes for itself isn't returned, so pass your own when you retry outside the client.

Attributes:

NameTypeDescription
nameA coarse category of the failure.
codePostHog's stable error code.
messageWhat went wrong. It never contains the secret key or the request body.
status_codeThe HTTP status of the response, or None when none arrived.
whyPostHog's explanation of the failure, when it gave one.
fixWhat to change to fix it, when PostHog said.
docs_urlA docs page about the error, when PostHog gave one.
fieldThe request field the error is about, when there is one.
retry_afterSeconds to wait before retrying, when PostHog said.

posthog.emails.EmailError.code

Python
code = code

posthog.emails.EmailError.docs_url

Python
docs_url = docs_url

posthog.emails.EmailError.field

Python
field = field

posthog.emails.EmailError.fix

Python
fix = fix

posthog.emails.EmailError.message

Python
message = message

posthog.emails.EmailError.name

Python
name = name

posthog.emails.EmailError.retry_after

Python
retry_after = retry_after

posthog.emails.EmailError.status_code

Python
status_code = status_code

posthog.emails.EmailError.why

Python
why = why

SendEmailResult

Python
SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = ()) -> None

The queued email. id is its message ID.

Attributes:

NameTypeDescription
idstrThe email's message ID.
replayedboolTrue when the response says PostHog replayed an earlier send for the same idempotency_key instead of sending again.
warningstuple[EmailWarning, ...]Warnings PostHog returned about the request.

posthog.emails.SendEmailResult.id

Python
id: str

posthog.emails.SendEmailResult.replayed

Python
replayed: bool = False

posthog.emails.SendEmailResult.warnings

Python
warnings: tuple[EmailWarning, ...] = ()

EmailWarning

Python
EmailWarning(code: str, message: str, fix: Optional[str] = None) -> None

A warning PostHog returned about a send that it queued. The client also logs it.

Attributes:

NameTypeDescription
codestrPostHog's stable warning code.
messagestrWhat PostHog warns about.
fixOptional[str]What to change, when PostHog said.

posthog.emails.EmailWarning.code

Python
code: str

posthog.emails.EmailWarning.fix

Python
fix: Optional[str] = None

posthog.emails.EmailWarning.message

Python
message: str

EmailStatus

Python
EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None) -> None

What happened to an email that send() queued.

status is one of:

  • queued: the email waits to go out.
  • sent: PostHog handed the email to the email provider.
  • failed: the email was not sent, and reason says why.
  • delivered: the recipient's mail server accepted the email.
  • bounced and complained: the recipient's mail provider reported them after delivery.

Later SDK versions can see values this list does not have yet. reason says why a failed email was not sent, such as provider_error or recipient_suppressed, or gives the bounce type of a bounced email: hard, soft or unknown. It is None otherwise.

Attributes:

NameTypeDescription
idstrThe email's message ID.
statusstrWhere the email is now, one of the values above.
created_atdatetimeWhen PostHog queued the email.
status_atdatetimeWhen the email reached its current status.
reasonOptional[str]Why a failed email was not sent, or a bounced email's bounce type.

posthog.emails.EmailStatus.created_at

Python
created_at: datetime

posthog.emails.EmailStatus.id

Python
id: str

posthog.emails.EmailStatus.reason

Python
reason: Optional[str] = None

posthog.emails.EmailStatus.status

Python
status: str

posthog.emails.EmailStatus.status_at

Python
status_at: datetime

OptionalSetArgs

Bases: TypedDict

Optional arguments for the set method.

Parameters:

NameDescription
distinct_idUnique identifier for the user to set properties on. If not set, the context distinct_id is used, if available, otherwise this function does nothing. Setting context-level distinct_id's is recommended.
propertiesDictionary of properties to set on the person
timestampWhen the properties were set (defaults to current time). UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
uuidUnique identifier for this operation. If not provided, one is generated. This UUID is returned, so you can correlate it with actions in your app. 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_geoipWhether to disable GeoIP lookup for this operation. Defaults to False.
optionsCapture options for this event, sent as given. See OptionalCaptureArgs. process_person_profile is True unless this call sets it.

Attributes:

NameTypeDescription
disable_geoipNotRequired[Optional[bool]]
distinct_idNotRequired[Optional[ID_TYPES]]
optionsNotRequired[Optional[Dict[str, Any]]]
propertiesNotRequired[Optional[Dict[str, Any]]]
timestampNotRequired[Optional[Union[datetime, str]]]
uuidNotRequired[Optional[Union[str, UUID]]]

posthog.args.OptionalSetArgs.disable_geoip

Python
disable_geoip: NotRequired[Optional[bool]]

posthog.args.OptionalSetArgs.distinct_id

Python
distinct_id: NotRequired[Optional[ID_TYPES]]

posthog.args.OptionalSetArgs.options

Python
options: NotRequired[Optional[Dict[str, Any]]]

posthog.args.OptionalSetArgs.properties

Python
properties: NotRequired[Optional[Dict[str, Any]]]

posthog.args.OptionalSetArgs.timestamp

Python
timestamp: NotRequired[Optional[Union[datetime, str]]]

posthog.args.OptionalSetArgs.uuid

Python
uuid: NotRequired[Optional[Union[str, UUID]]]

TemplateEmailArgs

Bases: _RecipientArgs

A send of an email template made in PostHog, named by its ID.

Parameters:

NameDescription
toOne recipient email address.
template_idThe UUID of a template made transactional in PostHog.
template_dataValues for the template's {{ variables.* }} placeholders.
distinct_idThe recipient's distinct ID in your product.
idempotency_key1 to 255 visible ASCII characters.
max_retriesOverrides the client's maximum number of retries for this send. 0 turns retries off.

Attributes:

NameTypeDescription
distinct_idNotRequired[Optional[str]]
idempotency_keyNotRequired[Optional[str]]
max_retriesNotRequired[Optional[int]]
template_dataNotRequired[Optional[Mapping[str, Any]]]
template_idUnion[str, UUID]
tostr

posthog.emails.TemplateEmailArgs.distinct_id

Python
distinct_id: NotRequired[Optional[str]]

posthog.emails.TemplateEmailArgs.idempotency_key

Python
idempotency_key: NotRequired[Optional[str]]

posthog.emails.TemplateEmailArgs.max_retries

Python
max_retries: NotRequired[Optional[int]]

posthog.emails.TemplateEmailArgs.template_data

Python
template_data: NotRequired[Optional[Mapping[str, Any]]]

posthog.emails.TemplateEmailArgs.template_id

Python
template_id: Union[str, UUID]

posthog.emails.TemplateEmailArgs.to

Python
to: str

CodeEmailArgs

Bases: _RecipientArgs

A send of email content that your code rendered for one recipient, named by a key.

The content goes out as is. To send a React email, render it to HTML in your app first.

An optional field passed as None counts as left out.

A PostHog version that doesn't take a field yet, such as cc, refuses the send with an error that names the field in EmailError.field. It never drops the field and sends the rest.

Parameters:

NameDescription
toOne recipient email address.
template_keyNames the email, so its metrics, logs and status group under it. Letters, digits, - and _, at most 400.
subjectThe subject line.
htmlThe HTML body. Give html, text or both.
textThe plain-text body. Without it, PostHog derives it from html. HTML with no text in it, such as a single image, goes out without a plain-text part.
from_A verified sender, such as "Acme <hello@example.com>".
reply_toOne address or a list of addresses. An empty list sends no reply-to.
ccOne address or a list of addresses that get a visible copy, at most 10.
bccOne address or a list of addresses that get a hidden copy, at most 10.
attachmentsFiles sent with the email: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files. The client checks both before any request. It uploads each file that PostHog doesn't hold yet, then sends the email. A file the client can't send raises EmailError with code invalid_attachment.
capture_engagementDeprecated, use tracking={"engagement": False}. It keeps working, but PostHog refuses a send that sets both capture_engagement and tracking. Captures the email's engagement events as events of the recipient. Defaults to True. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it.
sensitiveMarks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless tracking turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose template_key matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it.
trackingWhat PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. True turns on opens, clicks and engagement events. False turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An EmailTracking dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it.
distinct_idThe recipient's distinct ID in your product.
idempotency_key1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for another email, or for a template_id send, raises idempotency_key_reused. A retry with the same key returns the first send's result, also when its workflow was paused since.
max_retriesOverrides the client's maximum number of retries for this send. 0 turns retries off.

Attributes:

NameTypeDescription
attachmentsNotRequired[Optional[Sequence[EmailAttachment]]]
bccNotRequired[Optional[Union[str, Sequence[str]]]]
capture_engagementNotRequired[Optional[bool]]
ccNotRequired[Optional[Union[str, Sequence[str]]]]
distinct_idNotRequired[Optional[str]]
from_NotRequired[Optional[str]]
htmlNotRequired[Optional[str]]
idempotency_keyNotRequired[Optional[str]]
max_retriesNotRequired[Optional[int]]
reply_toNotRequired[Optional[Union[str, Sequence[str]]]]
sensitiveNotRequired[Optional[bool]]
subjectstr
template_keystr
textNotRequired[Optional[str]]
tostr
trackingNotRequired[Optional[Union[bool, EmailTracking]]]

posthog.emails.CodeEmailArgs.attachments

Python
attachments: NotRequired[Optional[Sequence[EmailAttachment]]]

posthog.emails.CodeEmailArgs.bcc

Python
bcc: NotRequired[Optional[Union[str, Sequence[str]]]]

posthog.emails.CodeEmailArgs.capture_engagement

Python
capture_engagement: NotRequired[Optional[bool]]

posthog.emails.CodeEmailArgs.cc

Python
cc: NotRequired[Optional[Union[str, Sequence[str]]]]

posthog.emails.CodeEmailArgs.distinct_id

Python
distinct_id: NotRequired[Optional[str]]

posthog.emails.CodeEmailArgs.from_

Python
from_: NotRequired[Optional[str]]

posthog.emails.CodeEmailArgs.html

Python
html: NotRequired[Optional[str]]

posthog.emails.CodeEmailArgs.idempotency_key

Python
idempotency_key: NotRequired[Optional[str]]

posthog.emails.CodeEmailArgs.max_retries

Python
max_retries: NotRequired[Optional[int]]

posthog.emails.CodeEmailArgs.reply_to

Python
reply_to: NotRequired[Optional[Union[str, Sequence[str]]]]

posthog.emails.CodeEmailArgs.sensitive

Python
sensitive: NotRequired[Optional[bool]]

posthog.emails.CodeEmailArgs.subject

Python
subject: str

posthog.emails.CodeEmailArgs.template_key

Python
template_key: str

posthog.emails.CodeEmailArgs.text

Python
text: NotRequired[Optional[str]]

posthog.emails.CodeEmailArgs.to

Python
to: str

posthog.emails.CodeEmailArgs.tracking

Python
tracking: NotRequired[Optional[Union[bool, EmailTracking]]]

EmailTracking

Bases: TypedDict

Which kinds of tracking a send with template_key turns on.

A key you leave out keeps its default.

Parameters:

NameDescription
opensCounts opens with PostHog's open pixel. Defaults to True.
clicksCounts clicks by sending the email's links through PostHog's click tracking. Defaults to False for a sensitive email and True for any other. Needs opens: PostHog refuses a send with opens=False and clicks=True.
engagementCaptures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to True. A project whose admin turned engagement capture off captures nothing, whatever the send asks.

Attributes:

NameTypeDescription
clicksbool
engagementbool
opensbool

posthog.emails.EmailTracking.clicks

Python
clicks: bool

posthog.emails.EmailTracking.engagement

Python
engagement: bool

posthog.emails.EmailTracking.opens

Python
opens: bool

EmailAttachment

Bases: TypedDict

A file sent with the email.

Parameters:

NameDescription
filenameThe file name the recipient sees, such as invite.ics.
contentThe file as bytes, bytearray or memoryview, or Base64 encoded as a string on one line with its padding, as base64.b64encode gives. PostHog can't fetch a file from a path or URL.
content_typeThe MIME type. Without it, the type follows the file name.
content_idShows the file inline: reference it in html as <img src="cid:logo"> with content_id logo.

Attributes:

NameTypeDescription
contentUnion[bytes, bytearray, memoryview, str]
content_idNotRequired[str]
content_typeNotRequired[str]
filenamestr

posthog.emails.EmailAttachment.content

Python
content: Union[bytes, bytearray, memoryview, str]

posthog.emails.EmailAttachment.content_id

Python
content_id: NotRequired[str]

posthog.emails.EmailAttachment.content_type

Python
content_type: NotRequired[str]

posthog.emails.EmailAttachment.filename

Python
filename: str

Was this page useful?