PostHog Python SDK - PostHog

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

Clientpublic

Initialize a new PostHog client instance.

Parameters

NameType
project_api_key?str

The project API key.

hostany

The host to use for the client.

debugbool

Whether to enable debug mode.

max_queue_sizeint
sendbool
on_errorany
flush_atint
flush_intervalfloat
gzipbool
max_retriesint
sync_modebool
timeoutint
threadint
poll_intervalint
personal_api_keyany
disabledbool
disable_geoipbool
historical_migrationbool
feature_flags_request_timeout_secondsint
super_propertiesany
enable_exception_autocapturebool
log_captured_exceptionsbool
project_rootany
privacy_modebool
before_sendany
flag_fallback_cache_urlany
enable_local_evaluationbool
capture_exception_code_variablesbool
code_variables_mask_patternsany
code_variables_ignore_patternsany

Examples

Returns

Capture methods

Examples

Returns

Contexts methods

new_contextpublic

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

Parameters

NameType
freshbool

Whether to create a fresh context that doesn't inherit from parent.

capture_exceptionsbool

Whether to automatically capture exceptions in this context.

Examples

Returns

Error Tracking methods

capture_exceptionpublic

Capture an exception for error tracking.

Parameters

Examples

Returns

Feature flags methods

feature_enabledpublic

Check if a feature flag is enabled for a user.

Parameters

NameType
key?any

The feature flag key.

distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

send_feature_flag_eventsbool

Whether to send feature flag events.

disable_geoipany

Whether to disable GeoIP for this request.

Examples

Returns

get_all_flagspublic

Get all feature flags for a user.

Parameters

NameType
distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Examples

Returns

Type
Optional[dict[str, Union[bool, str]]]

get_all_flags_and_payloadspublic

Get all feature flags and their payloads for a user.

Parameters

NameType
distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Examples

Returns

get_feature_flagpublic

Get multivariate feature flag value for a user.

Parameters

NameType
key?any

The feature flag key.

distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

send_feature_flag_eventsbool

Whether to send feature flag events.

disable_geoipany

Whether to disable GeoIP for this request.

Examples

Returns

Type
Union[bool, str, any]

get_feature_flag_payloadpublic

Get the payload for a feature flag.

Parameters

NameType
key?any

The feature flag key.

distinct_id?any

The distinct ID of the user.

match_valuebool

The specific flag value to get payload for.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

send_feature_flag_eventsbool

Whether to send feature flag events.

disable_geoipany

Whether to disable GeoIP for this request.

Examples

Returns

get_feature_flags_and_payloadspublic

Get feature flags and payloads for a user by calling decide.

Parameters

NameType
distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Examples

Returns

get_feature_payloadspublic

Get feature flag payloads for a user by calling decide.

Parameters

NameType
distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Examples

Returns

get_feature_variantspublic

Get feature flag variants for a user by calling decide.

Parameters

NameType
distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Returns

Type
dict[str, Union[bool, str]]

get_flags_decisionpublic

Get feature flags decision.

Parameters

NameType
distinct_idNumber

The distinct ID of the user.

groups?dict

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

disable_geoipany

Whether to disable GeoIP for this request.

flag_keys_to_evaluate?list[str]

A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.

Examples

Returns

load_feature_flagspublic

Load feature flags for local evaluation.

Examples

Returns

Identification methods

aliaspublic

Create an alias between two distinct IDs.

Parameters

NameType
previous_id?str

The previous distinct ID.

distinct_id?str

The new distinct ID to alias to.

timestampany

The timestamp of the event.

uuidany

A unique identifier for the event.

disable_geoipany

Whether to disable GeoIP for this event.

Examples

Returns

group_identifypublic

Identify a group and set its properties.

Parameters

NameType
group_type?str

The type of group (e.g., 'company', 'team').

group_key?str

The unique identifier for the group.

properties?dict[str, Any]

A dictionary of properties to set on the group.

timestampdatetime

The timestamp of the event.

uuid?str

A unique identifier for the event.

disable_geoip?bool

Whether to disable GeoIP for this event.

distinct_idNumber

The distinct ID of the user performing the action.

Examples

Returns

setpublic

Set properties on a person profile.

Parameters

Examples

Returns

set_oncepublic

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

Parameters

Examples

Returns

Other methods

flushpublic

Force a flush from the internal queue to the server. Do not use directly, call shutdown() instead.

Examples

Returns

get_feature_flag_resultpublic

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

NameType
key?any

The feature flag key.

distinct_id?any

The distinct ID of the user.

groupsany

A dictionary of group information.

person_propertiesany

A dictionary of person properties.

group_propertiesany

A dictionary of group properties.

only_evaluate_locallybool

Whether to only evaluate locally.

send_feature_flag_eventsbool

Whether to send feature flag events.

disable_geoipany

Whether to disable GeoIP for this request.

Examples

Returns

joinpublic

End the consumer thread once the queue is empty. Do not use directly, call shutdown() instead.

Examples

Returns

shutdownpublic

Flush all messages and cleanly shutdown the client. Call this before the process ends in serverless environments to avoid data loss.

Examples

Returns

PostHog Module Functions

Global functions available in the PostHog module

Client management methods

flushpublic

Tell the client to flush all queued events.

Examples

Returns

joinpublic

Block program until the client clears the queue. Used during program shutdown. You should use shutdown() directly in most cases.

Examples

Returns

shutdownpublic

Flush all messages and cleanly shutdown the client.

Examples

Returns

Contexts methods

new_contextpublic

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

Parameters

NameType
freshbool

Whether to start with a fresh context (default: False)

capture_exceptionsbool

Whether to capture exceptions raised within the context (default: True)

clientany

Optional Posthog client instance to use for this context (default: None)

Examples

Returns

scopedpublic

Decorator that creates a new context for the function.

Parameters

NameType
freshbool

Whether to start with a fresh context (default: False)

capture_exceptionsbool

Whether to capture and track exceptions with posthog error tracking (default: True)

Examples

Returns

set_context_sessionpublic

Set the session ID for the current context.

Parameters

NameType
session_id?str

The session ID to associate with the current context and its children

Examples

Returns

tagpublic

Add a tag to the current context.

Parameters

NameType
name?str

The tag key

value?Any

The tag value

Examples

Returns

Events methods

capturepublic

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

NameType
event?str

The event name to specify the event **kwargs: Optional arguments including:

kwargs?Unpack[OptionalCaptureArgs]

Examples

Returns

capture_exceptionpublic

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

NameType
exceptionBaseException

The exception to capture. If not provided, the current exception is captured via sys.exc_info()

kwargs?Unpack[OptionalCaptureArgs]

Examples

Returns

Feature flags methods

feature_enabledpublic

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

NameType
key?any

The feature flag key

distinct_id?any

The user's distinct ID

groupsany

Groups mapping

person_propertiesany

Person properties

group_propertiesany

Group properties

only_evaluate_locallybool

Whether to evaluate only locally

send_feature_flag_eventsbool

Whether to send feature flag events

disable_geoipany

Whether to disable GeoIP lookup

Examples

Returns

feature_flag_definitionspublic

Returns loaded feature flags.

Notes:

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

Examples

Returns

get_all_flagspublic

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

NameType
distinct_id?any

The user's distinct ID

groupsany

Groups mapping

person_propertiesany

Person properties

group_propertiesany

Group properties

only_evaluate_locallybool

Whether to evaluate only locally

disable_geoipany

Whether to disable GeoIP lookup

Examples

Returns

get_feature_flagpublic

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

NameType
key?any

The feature flag key

distinct_id?any

The user's distinct ID

groupsany

Groups mapping from group type to group key

person_propertiesany

Person properties

group_propertiesany

Group properties in format { group_type_name: { group_properties } }

only_evaluate_locallybool

Whether to evaluate only locally

send_feature_flag_eventsbool

Whether to send feature flag events

disable_geoipany

Whether to disable GeoIP lookup

Examples

Returns

load_feature_flagspublic

Load feature flag definitions from PostHog.

Examples

Returns

Identification methods

aliaspublic

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

NameType
previous_id?any

The unique ID of the user before

distinct_id?any

The current unique id

timestampany

Optional timestamp for the event

uuidany

Optional UUID for the event

disable_geoipany

Whether to disable GeoIP lookup

Examples

Returns

group_identifypublic

Set properties on a group.

Parameters

NameType
group_type?any

Type of your group

group_key?any

Unique identifier of the group

propertiesany

Properties to set on the group

timestampany

Optional timestamp for the event

uuidany

Optional UUID for the event

disable_geoipany

Whether to disable GeoIP lookup

Examples

Returns

identify_contextpublic

Identify the current context with a distinct ID.

Parameters

NameType
distinct_id?str

The distinct ID to associate with the current context and its children

Examples

Returns

setpublic

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

Examples

Returns

set_oncepublic

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

Examples

Returns

Other methods

get_feature_flag_resultpublic

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 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}")

Parameters

NameType
key?any
distinct_id?any
groupsany
person_propertiesany
group_propertiesany
only_evaluate_locallybool
send_feature_flag_eventsbool
disable_geoipany

Returns

get_remote_config_payloadpublic

Get the payload for a remote config feature flag.

Parameters

NameType
key?any

The key of the feature flag

Returns

set_capture_exception_code_variables_contextpublic

Set whether code variables are captured for the current context.

Parameters

Returns

set_code_variables_ignore_patterns_contextpublic

Variable names matching these patterns will be ignored completely when capturing code variables.

Parameters

NameType
ignore_patterns?list

Returns

set_code_variables_mask_patterns_contextpublic

Variable names matching these patterns will be masked with *** when capturing code variables.

Parameters

NameType
mask_patterns?list

Returns