PostHog Python SDK
PostHog
This is the SDK reference for the PostHog Python SDK. You can learn more about example usage in the Python SDK documentation. You can also follow Flask and Django guides to integrate PostHog into your project.
Initialization methods
Client
public
Initialize a new PostHog client instance.
Parameters
Name | Type |
---|---|
project_api_key? | str |
The project API key. | |
host | any |
The host to use for the client. | |
debug | bool |
Whether to enable debug mode. | |
max_queue_size | int |
Parameter: max_queue_size | |
send | bool |
Parameter: send | |
on_error | any |
Parameter: on_error | |
flush_at | int |
Parameter: flush_at | |
flush_interval | float |
Parameter: flush_interval | |
gzip | bool |
Parameter: gzip | |
max_retries | int |
Parameter: max_retries | |
sync_mode | bool |
Parameter: sync_mode | |
timeout | int |
Parameter: timeout | |
thread | int |
Parameter: thread | |
poll_interval | int |
Parameter: poll_interval | |
personal_api_key | any |
Parameter: personal_api_key | |
disabled | bool |
Parameter: disabled | |
disable_geoip | bool |
Parameter: disable_geoip | |
historical_migration | bool |
Parameter: historical_migration | |
feature_flags_request_timeout_seconds | int |
Parameter: feature_flags_request_timeout_seconds | |
super_properties | any |
Parameter: super_properties | |
enable_exception_autocapture | bool |
Parameter: enable_exception_autocapture | |
log_captured_exceptions | bool |
Parameter: log_captured_exceptions | |
project_root | any |
Parameter: project_root | |
privacy_mode | bool |
Parameter: privacy_mode | |
before_send | any |
Parameter: before_send | |
flag_fallback_cache_url | any |
Parameter: flag_fallback_cache_url |
Examples
from posthog import Posthogposthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')
Returns
Type |
---|
None |
Capture methods
capture
public
Captures an event manually. Learn about capture best practices
Parameters
Name | Type |
---|---|
event? | str |
The event name to capture. | |
kwargs? | typing_extensions.Unpack[OptionalCaptureArgs] |
Parameter: kwargs |
Examples
# Anonymous eventposthog.capture('some-anon-event')
Returns
Type |
---|
Optional[str] |
Contexts methods
new_context
public
Create a new context for managing shared state. Learn more about contexts.
Parameters
Name | Type |
---|---|
fresh | bool |
Whether to create a fresh context that doesn't inherit from parent. | |
capture_exceptions | bool |
Whether to automatically capture exceptions in this context. |
Examples
with posthog.new_context():identify_context('<distinct_id>')posthog.capture('event_name')
Returns
Type |
---|
None |
Error Tracking methods
capture_exception
public
Capture an exception for error tracking.
Parameters
Name | Type |
---|---|
exception? | BaseException |
The exception to capture. | |
kwargs? | typing_extensions.Unpack[OptionalCaptureArgs] |
Parameter: kwargs |
Examples
try:# Some code that might failpassexcept Exception as e:posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)
Returns
Type |
---|
None |
Feature Flags methods
feature_enabled
public
Check if a feature flag is enabled for a user.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key. | |
distinct_id? | any |
The distinct ID of the user. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
send_feature_flag_events | bool |
Whether to send feature flag events. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')if is_my_flag_enabled:# Do something differently for this user# Optional: fetch the payloadmatched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
Returns
Type |
---|
None |
get_all_flags
public
Get all feature flags for a user.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The distinct ID of the user. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
posthog.get_all_flags('distinct_id_of_your_user')
Returns
Type |
---|
Optional[dict[str, Union[bool, str]]] |
get_all_flags_and_payloads
public
Get all feature flags and their payloads for a user.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The distinct ID of the user. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')
Returns
Type |
---|
FlagsAndPayloads |
get_feature_flag
public
Get multivariate feature flag value for a user.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key. | |
distinct_id? | any |
The distinct ID of the user. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
send_feature_flag_events | bool |
Whether to send feature flag events. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
enabled_variant = posthog.get_feature_flag('flag-key', 'distinct_id_of_your_user')if enabled_variant == 'variant-key': # replace 'variant-key' with the key of your variant# Do something differently for this user# Optional: fetch the payloadmatched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
Returns
Type |
---|
Union[bool, str, any] |
get_feature_flag_payload
public
Get the payload for a feature flag.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key. | |
distinct_id? | any |
The distinct ID of the user. | |
match_value | bool |
The specific flag value to get payload for. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
send_feature_flag_events | bool |
Whether to send feature flag events. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')if is_my_flag_enabled:# Do something differently for this user# Optional: fetch the payloadmatched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
Returns
Type |
---|
None |
get_feature_flags_and_payloads
public
Get feature flags and payloads for a user by calling decide.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The distinct ID of the user. | |
groups | any |
A dictionary of group information. | |
person_properties | any |
A dictionary of person properties. | |
group_properties | any |
A dictionary of group properties. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
result = posthog.get_feature_flags_and_payloads('<distinct_id>')
Returns
Type |
---|
FlagsAndPayloads |
get_feature_payloads
public
Get feature flag payloads for a user by calling decide.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The distinct ID of the user. | |
groups | any |
A dictionary of group information. | |
person_properties | any |
A dictionary of person properties. | |
group_properties | any |
A dictionary of group properties. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
payloads = posthog.get_feature_payloads('<distinct_id>')
Returns
Type |
---|
dict[str, str] |
get_feature_variants
public
Get feature flag variants for a user by calling decide.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The distinct ID of the user. | |
groups | any |
A dictionary of group information. | |
person_properties | any |
A dictionary of person properties. | |
group_properties | any |
A dictionary of group properties. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Returns
Type |
---|
dict[str, Union[bool, str]] |
get_flags_decision
public
Get feature flags decision.
Parameters
Name | Type |
---|---|
distinct_id | Number |
The distinct ID of the user. | |
groups? | dict |
A dictionary of group information. | |
person_properties | any |
A dictionary of person properties. | |
group_properties | any |
A dictionary of group properties. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
decision = posthog.get_flags_decision('user123')
Returns
Type |
---|
FlagsResponse |
load_feature_flags
public
Load feature flags for local evaluation.
Examples
posthog.load_feature_flags()
Returns
Type |
---|
None |
Identification methods
alias
public
Create an alias between two distinct IDs.
Parameters
Name | Type |
---|---|
previous_id? | str |
The previous distinct ID. | |
distinct_id? | str |
The new distinct ID to alias to. | |
timestamp | any |
The timestamp of the event. | |
uuid | any |
A unique identifier for the event. | |
disable_geoip | any |
Whether to disable GeoIP for this event. |
Examples
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')
Returns
Type |
---|
None |
group_identify
public
Identify a group and set its properties.
Parameters
Name | Type |
---|---|
group_type? | str |
The type of group (e.g., 'company', 'team'). | |
group_key? | str |
The unique identifier for the group. | |
properties | any |
A dictionary of properties to set on the group. | |
timestamp | any |
The timestamp of the event. | |
uuid | any |
A unique identifier for the event. | |
disable_geoip | any |
Whether to disable GeoIP for this event. | |
distinct_id | any |
The distinct ID of the user performing the action. |
Examples
posthog.group_identify('company', 'company_id_in_your_db', {'name': 'Awesome Inc.','employees': 11})
Returns
Type |
---|
None |
set
public
Set properties on a person profile.
Parameters
Name | Type |
---|---|
kwargs? | typing_extensions.Unpack[OptionalSetArgs] |
Parameter: kwargs |
Examples
# Set with distinct idposthog.capture('event_name',distinct_id='user-distinct-id',properties={'$set': {'name': 'Max Hedgehog'},'$set_once': {'initial_url': '/blog'}})
Returns
Type |
---|
Optional[str] |
set_once
public
Set properties on a person profile only if they haven't been set before.
Parameters
Name | Type |
---|---|
kwargs? | typing_extensions.Unpack[OptionalSetArgs] |
Parameter: kwargs |
Examples
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})
Returns
Type |
---|
Optional[str] |
Other methods
flush
public
Force a flush from the internal queue to the server. Do not use directly, call shutdown()
instead.
Examples
posthog.capture('event_name')posthog.flush() # Ensures the event is sent immediately
Returns
Type |
---|
None |
get_feature_flag_result
public
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
.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key. | |
distinct_id? | any |
The distinct ID of the user. | |
groups | dict |
A dictionary of group information. | |
person_properties | dict |
A dictionary of person properties. | |
group_properties | dict |
A dictionary of group properties. | |
only_evaluate_locally | bool |
Whether to only evaluate locally. | |
send_feature_flag_events | bool |
Whether to send feature flag events. | |
disable_geoip | any |
Whether to disable GeoIP for this request. |
Examples
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 payloadmatched_flag_payload = flag_result.payload
Returns
Type |
---|
Optional[FeatureFlagResult] |
join
public
End the consumer thread once the queue is empty. Do not use directly, call shutdown()
instead.
Examples
posthog.join()
Returns
Type |
---|
None |
shutdown
public
Flush all messages and cleanly shutdown the client. Call this before the process ends in serverless environments to avoid data loss.
Examples
posthog.shutdown()
Returns
Type |
---|
None |
PostHog Module Functions
Global functions available in the PostHog module
Client management methods
flush
public
Tell the client to flush.
Examples
from posthog import flushflush()
Returns
Type |
---|
None |
join
public
Block program until the client clears the queue.
Examples
from posthog import joinjoin()
Returns
Type |
---|
None |
shutdown
public
Flush all messages and cleanly shutdown the client.
Examples
from posthog import shutdownshutdown()
Returns
Type |
---|
None |
Contexts methods
new_context
public
Create a new context scope that will be active for the duration of the with block.
Parameters
Name | Type |
---|---|
fresh | bool |
Whether to start with a fresh context (default: False) | |
capture_exceptions | bool |
Whether to capture exceptions raised within the context (default: True) |
Examples
from posthog import new_context, tag, capturewith new_context():tag("request_id", "123")capture("event_name", properties={"property": "value"})
Returns
Type |
---|
None |
scoped
public
Decorator that creates a new context for the function.
Parameters
Name | Type |
---|---|
fresh | bool |
Whether to start with a fresh context (default: False) | |
capture_exceptions | bool |
Whether to capture and track exceptions with posthog error tracking (default: True) |
Examples
from posthog import scoped, tag, capture@scoped()def process_payment(payment_id):tag("payment_id", payment_id)capture("payment_started")
Returns
Type |
---|
None |
set_context_session
public
Set the session ID for the current context.
Parameters
Name | Type |
---|---|
session_id? | str |
The session ID to associate with the current context and its children |
Examples
from posthog import set_context_sessionset_context_session("session_123")
Returns
Type |
---|
None |
tag
public
Add a tag to the current context.
Parameters
Name | Type |
---|---|
name? | str |
The tag key | |
value? | typing.Any |
The tag value |
Examples
from posthog import tagtag("user_id", "123")
Returns
Type |
---|
None |
Events methods
capture
public
Capture anything a user does within your system.
Notes:
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.
Parameters
Name | Type |
---|---|
event? | str |
The event name to specify the event **kwargs: Optional arguments including: | |
kwargs? | typing_extensions.Unpack[OptionalCaptureArgs] |
Parameter: kwargs |
Examples
# Context and capture usagefrom posthog import new_context, identify_context, tag_context, 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_ididentify_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 propertiescapture('movie played', properties={'movie_id': '123', 'category': 'romcom'})# Capture an event with some propertiescapture('purchase', properties={'product_id': '123', 'category': 'romcom'})# Capture an event with some associated groupcapture('purchase', groups={'company': 'id:5'})# Adding a tag to the current context will cause it to appear on all subsequent eventstag_context('some-tag', 'some-value')capture('another-event') # Will be captured with `'some-tag': 'some-value'` in the properties dict
Returns
Type |
---|
Optional[str] |
capture_exception
public
Capture exceptions that happen in your code.
Notes:
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
.
Parameters
Name | Type |
---|---|
exception | BaseException |
The exception to capture. If not provided, the current exception is captured via | |
kwargs? | typing_extensions.Unpack[OptionalCaptureArgs] |
Parameter: kwargs |
Examples
# Capture exceptionfrom posthog import capture_exceptiontry:risky_operation()except Exception as e:capture_exception(e)
Returns
Type |
---|
None |
Feature flags methods
feature_enabled
public
Use feature flags to enable or disable features for users.
Notes:
You can call posthog.load_feature_flags()
before to make sure you're not doing unexpected requests.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key | |
distinct_id? | any |
The user's distinct ID | |
groups | dict |
Groups mapping | |
person_properties | dict |
Person properties | |
group_properties | dict |
Group properties | |
only_evaluate_locally | bool |
Whether to evaluate only locally | |
send_feature_flag_events | bool |
Whether to send feature flag events | |
disable_geoip | any |
Whether to disable GeoIP lookup |
Examples
# Boolean feature flagfrom posthog import feature_enabled, get_feature_flag_payloadis_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')
Returns
Type |
---|
None |
feature_flag_definitions
public
Returns loaded feature flags.
Notes:
Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.
Examples
from posthog import feature_flag_definitionsdefinitions = feature_flag_definitions()
Returns
Type |
---|
None |
get_all_flags
public
Get all flags for a given user.
Notes:
Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.
Parameters
Name | Type |
---|---|
distinct_id? | any |
The user's distinct ID | |
groups | dict |
Groups mapping | |
person_properties | dict |
Person properties | |
group_properties | dict |
Group properties | |
only_evaluate_locally | bool |
Whether to evaluate only locally | |
disable_geoip | any |
Whether to disable GeoIP lookup |
Examples
# All flags for userfrom posthog import get_all_flagsget_all_flags('distinct_id_of_your_user')
Returns
Type |
---|
Optional[dict[str, FeatureFlag]] |
get_feature_flag
public
Get feature flag variant for users. Used with experiments.
Notes:
groups
are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. group_properties
take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}.
Parameters
Name | Type |
---|---|
key? | any |
The feature flag key | |
distinct_id? | any |
The user's distinct ID | |
groups | dict |
Groups mapping from group type to group key | |
person_properties | dict |
Person properties | |
group_properties | dict |
Group properties in format { group_type_name: { group_properties } } | |
only_evaluate_locally | bool |
Whether to evaluate only locally | |
send_feature_flag_events | bool |
Whether to send feature flag events | |
disable_geoip | any |
Whether to disable GeoIP lookup |
Examples
# Multivariate feature flagfrom posthog import get_feature_flag, get_feature_flag_payloadenabled_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')
Returns
Type |
---|
Optional[FeatureFlag] |
load_feature_flags
public
Load feature flag definitions from PostHog.
Examples
from posthog import load_feature_flagsload_feature_flags()
Returns
Type |
---|
None |
Identification methods
alias
public
Associate user behaviour before and after they e.g. register, login, or perform some other identifying action.
Notes:
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.
Parameters
Name | Type |
---|---|
previous_id? | any |
The unique ID of the user before | |
distinct_id? | any |
The current unique id | |
timestamp | any |
Optional timestamp for the event | |
uuid | any |
Optional UUID for the event | |
disable_geoip | any |
Whether to disable GeoIP lookup |
Examples
# Alias userfrom posthog import aliasalias(previous_id='distinct_id', distinct_id='alias_id')
Returns
Type |
---|
None |
group_identify
public
Set properties on a group.
Parameters
Name | Type |
---|---|
group_type? | any |
Type of your group | |
group_key? | any |
Unique identifier of the group | |
properties | any |
Properties to set on the group | |
timestamp | any |
Optional timestamp for the event | |
uuid | any |
Optional UUID for the event | |
disable_geoip | any |
Whether to disable GeoIP lookup |
Examples
# Group identifyfrom posthog import group_identifygroup_identify('company', 'company_id_in_your_db', {'name': 'Awesome Inc.','employees': 11})
Returns
Type |
---|
None |
identify_context
public
Identify the current context with a distinct ID.
Parameters
Name | Type |
---|---|
distinct_id? | str |
The distinct ID to associate with the current context and its children |
Examples
from posthog import identify_contextidentify_context("user_123")
Returns
Type |
---|
None |
set
public
Set properties on a user record.
Notes:
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).
Parameters
Name | Type |
---|---|
kwargs? | typing_extensions.Unpack[OptionalSetArgs] |
Parameter: kwargs |
Examples
# Set person propertiesfrom posthog import capturecapture('distinct_id',event='event_name',properties={'$set': {'name': 'Max Hedgehog'},'$set_once': {'initial_url': '/blog'}})
Returns
Type |
---|
Optional[str] |
set_once
public
Set properties on a user record, only if they do not yet exist.
Notes:
This will not overwrite previous people property values, unlike set
. Otherwise, operates in an identical manner to set
.
Parameters
Name | Type |
---|---|
kwargs? | typing_extensions.Unpack[OptionalSetArgs] |
Parameter: kwargs |
Examples
# Set property oncefrom posthog import capturecapture('distinct_id',event='event_name',properties={'$set': {'name': 'Max Hedgehog'},'$set_once': {'initial_url': '/blog'}})
Returns
Type |
---|
Optional[str] |
Other methods
get_remote_config_payload
public
Get the payload for a remote config feature flag.
Parameters
Name | Type |
---|---|
key? | any |
The key of the feature flag |
Returns
Type |
---|
None |