Python

Last updated:

|Edit this page|
Which features are available in this library?
  • Event capture
  • User identification
  • Feature flags
  • Group analytics
  • Surveys
  • LLM observability
  • Error tracking

The Python SDK makes it easy to capture events, evaluate feature flags, track errors, and more in your Python apps.

Installation

Terminal
pip install posthog

In your app, import the posthog library and set your project API key and host before making any calls.

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

Note: As a rule of thumb, we do not recommend having API keys in plaintext. Setting it as an environment variable is best.

You can find your project API key and instance address in the project settings page in PostHog.

To debug, you can toggle debug mode:

Python
posthog.debug = True

To make sure no calls happen during tests, you can disable PostHog, like so:

Python
if settings.TEST:
posthog.disabled = True

Capturing events

You can send custom events using capture:

Python
# Events captured with no context or explicit distinct_id are marked as personless and have an auto-generated distinct_id:
posthog.capture('some-anon-event')
from posthog import identify_context, new_context
# Use contexts to manage user identification across multiple capture calls
with new_context():
identify_context('distinct_id_of_the_user')
posthog.capture('user_signed_up')
posthog.capture('user_logged_in')
# You can also capture events with a specific distinct_id
posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')

Tip: We recommend using a [object] [verb] format for your event names, where [object] is the entity that the behavior relates to, and [verb] is the behavior itself. For example, project created, user signed up, or invite sent.

Setting event properties

Optionally, you can include additional information with the event by including a properties object:

Python
posthog.capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)

Sending page views

If you're aiming for a backend-only implementation of PostHog and won't be capturing events from your frontend, you can send pageviews from your backend like so:

Python
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})

Person profiles and properties

The Python SDK captures identified events if the current context is identified or if you pass a distinct ID explicitly. These create person profiles. To set person properties in these profiles, include them when capturing an event:

Python
# Passing a distinct id explicitly
posthog.capture(
'event_name',
distinct_id='user-distinct-id',
properties={
'$set': {'name': 'Max Hedgehog'},
'$set_once': {'initial_url': '/blog'}
}
)
# Using contexts
from posthog import new_context, identify_context
with new_context():
identify_context('user-distinct-id')
posthog.capture('event_name')

For more details on the difference between $set and $set_once, see our person properties docs.

To capture anonymous events without person profiles, set the event's $process_person_profile property to False. Events captured with no context or explicit distinct_id are marked as personless, and will have an auto-generated distinct_id:

Python
posthog.capture(
event='event_name',
properties={
'$process_person_profile': False
}
)

Alias

Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.

In this case, you can use alias to assign another distinct ID to the same user.

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

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Contexts

The Python SDK uses nested contexts for managing state that's shared across events. Contexts are the recommended way to manage things like "which user is taking this action" (through identify_context), rather than manually passing user state through your apps stack.

When events (including exceptions) are captured in a context, the event uses the user distinct ID, session ID, and tags that are (optionally) set in the context. This is useful for adding properties to multiple events during a single user's interaction with your product.

You can enter a context using the with statement:

Python
from posthog import new_context, tag, set_context_session, identify_context
with new_context():
tag("transaction_id", "abc123")
tag("some_arbitrary_value", {"tags": "can be dicts"})
# Sessions are UUIDv7 values and used to track a sequence of events that occur within a single user session
# See https://posthog.com/docs/data/sessions
set_context_session(session_id)
# Setting the context-level distinct ID. See below for more details.
identify_context(user_id)
# This event is captured with the distinct ID, session ID, and tags set above
posthog.capture("order_processed")

Contexts are persisted across function calls. If you enter one and then call a function and capture an event in the called function, it uses the context tags and session ID set in the parent context:

Python
from posthog import new_context, tag
def some_function():
# When called from `outer_function`, this event is captured with the property some-key="value-4"
posthog.capture("order_processed")
def outer_function():
with new_context():
tag("some-key", "value-4")
some_function()

Contexts are nested, so tags added to a parent context are inherited by child contexts. If you set the same tag in both a parent and child context, the child context's value overrides the parent's at event capture (but the parent context won't be affected). This nesting also applies to session IDs and distinct IDs.

Python
from posthog import new_context, tag
with new_context():
tag("some-key", "value-1")
tag("some-other-key", "another-value")
with new_context():
tag("some-key", "value-2")
# This event is captured with some-key="value-2" and some-other-key="another-value"
posthog.capture("order_processed")
# This event is captured with some-key="value-1" and some-other-key="another-value"
posthog.capture("order_processed")

You can disable this nesting behavior by passing fresh=True to new_context:

Python
from posthog import new_context
with new_context(fresh=True):
tag("some-key", "value-2")
# This event only has the property some-key="value-2" from the fresh context
posthog.capture("order_processed")

Note: Distinct IDs, session IDs, and properties passed directly to calls to capture and related functions override context state in the final event captured.

Contexts and user identification

Contexts can be associated with a distinct ID by calling posthog.identify_context:

Python
from posthog import identify_context
identify_context("distinct-id")

Within a context associated with a distinct ID, all events captured are associated with that user. You can override the distinct ID for a specific event by passing a distinct_id argument to capture:

Python
from posthog import new_context, identify_context
with new_context():
identify_context("distinct-id")
posthog.capture("order_processed") # will be associated with distinct-id
posthog.capture("order_processed", distinct_id="another-distinct-id") # will be associated with another-distinct-id

It's recommended to pass the currently active distinct ID from the frontend to the backend, using the X-POSTHOG-DISTINCT-ID header. If you're using our Django middleware, this is extracted and associated with the request handler context automatically.

You can read more about identifying users in the user identification documentation.

Contexts and sessions

Contexts can be associated with a session ID by calling posthog.set_context_session. Session IDs must be UUIDv7 strings.

Using PostHog on your frontend too? If you're using the PostHog JavaScript Web SDK on your frontend, it generates a session ID for you and you can retrieve it by calling posthog.get_session_id() there. We then recommend passing that session ID to your backend by setting the X-POSTHOG-SESSION-ID header and extracting it in your request handler (if you're using our Django middleware, this happens automatically).

Python
from posthog import new_context, set_context_session
with new_context():
set_context_session(request.get_header("X-POSTHOG-SESSION-ID"))

If you associate a context with a session, you'll be able to do things like:

  • See backend events on the session timeline when viewing session replays
  • View session replays for users that triggered a backend exception in error tracking

You can read more about sessions in the session tracking documentation.

Exception capture

By default exceptions raised within a context are captured and available in the error tracking dashboard. You can override this behavior by passing capture_exceptions=False to new_context:

Python
from posthog import new_context, tag
with new_context(capture_exceptions=False):
tag("transaction_id", "abc123")
tag("some_arbitrary_value", {"tags": "can be dicts"})
# This event will be captured with the tags set above
posthog.capture("order_processed")
# This exception will not be captured
raise Exception("Order processing failed")

Decorating functions

The SDK exposes a function decorator. It takes the same arguments as new_context and provides a handy way to mark a whole function as being in a new context. For example:

Python
from posthog import scoped, identify_context
@scoped(fresh=True)
def process_order(user, order_id):
identify_context(user.distinct_id)
posthog.capture("order_processed") # Associated with the user
raise Exception("Order processing failed") # This exception is also captured and associated with the user

Group analytics

Group analytics allows you to associate an event with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on our pricing page.

To capture an event and associate it with a group:

Python
posthog.capture('some_event', groups={'company': 'company_id_in_your_db'})

To update properties on a group:

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

The name is a special property which is used in the PostHog UI for the name of the group. If you don't specify a name property, the group ID will be used instead.

Feature flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

There are 2 steps to implement feature flags in Python:

Step 1: Evaluate the feature flag value

Boolean feature flags

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

Multivariate feature flags

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

Step 2: Include feature flag information when capturing events

If you want use your feature flag to breakdown or filter events in your insights, you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event.

Note: This step is only required for events captured using our server-side SDKs or API.

There are two methods you can use to include feature flag information in your events:

Method 1: Include the $feature/feature_flag_name property

In the event properties, include $feature/feature_flag_name: variant_key:

Python
posthog.capture(
distinct_id="distinct_id_of_the_user"
'event_name',
{
'$feature/feature-flag-key': 'variant-key' # replace feature-flag-key with your flag key. Replace 'variant-key' with the key of your variant
}
)

Method 2: Set send_feature_flags to true

The capture() method has an optional argument send_feature_flags, which is set to false by default. By setting this to true, feature flag information will automatically be sent with the event.

Note that by doing this, PostHog will make an additional request to fetch feature flag information before capturing the event. So this method is only recommended if you don't mind the extra API call and delay.

Python
posthog.capture(
distinct_id="distinct_id_of_the_user"
'event_name',
send_feature_flags=True
)

Fetching all flags for a user

You can fetch all flag values for a single user by calling get_all_flags() or get_all_flags_and_payloads().

This is useful when you need to fetch multiple flag values and don't want to make multiple requests.

Python
posthog.get_all_flags('distinct_id_of_your_user')
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')

Sending $feature_flag_called events

Capturing $feature_flag_called events enable PostHog to know when a flag was accessed by a user and thus provide analytics and insights on the flag. By default, we send a these event when:

  1. You call posthog.get_feature_flag() or posthog.feature_enabled(), AND
  2. It's a new user, or the value of the flag has changed.

Note: Tracking whether it's a new user or if a flag value has changed happens in a local cache. This means that if you reinitialize the PostHog client, the cache resets as well – causing $feature_flag_called events to be sent again when calling get_feature_flag or feature_enabled. PostHog is built to handle this, and so duplicate $feature_flag_called events won't affect your analytics.

You can disable automatically capturing $feature_flag_called events. For example, when you don't need the analytics, or it's being called at such a high volume that sending events slows things down.

To disable it, set the send_feature_flag_events argument in your function call, like so:

Python
is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user', send_feature_flag_events=False)
# will not send `$feature_flag_called` events

Advanced: Overriding server properties

Sometimes, you may want to evaluate feature flags using person properties, groups, or group properties that haven't been ingested yet, or were set incorrectly earlier.

You can provide properties to evaluate the flag with by using the person properties, groups, and group properties arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server.

For example:

Python
posthog.get_feature_flag(
'flag-key',
'distinct_id_of_the_user',
person_properties={'property_name': 'value'},
groups={
'your_group_type': 'your_group_id',
'another_group_type': 'your_group_id'},
group_properties={
'your_group_type': {'group_property_name': 'value'},
'another_group_type': {'group_property_name': 'value'}
},
)

Overriding GeoIP properties

By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties.

Currently PostHog does not provide a way to override GeoIP properties using our SDKs. Our API, however, does allow you do this. See our API docs on how to override GeoIP properties for more details.

Request timeout

You can configure the feature_flags_request_timeout_seconds parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.

Python
posthog = Posthog('<ph_project_api_key>',
host='https://us.i.posthog.com'
feature_flags_request_timeout_seconds=3 // Time in second. Default is 3
)

Error handling

When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:

Python
def handle_feature_flag(client, flag_key, distinct_id):
try:
is_enabled = client.is_feature_enabled(flag_key, distinct_id)
print(f"Feature flag '{flag_key}' for user '{distinct_id}' is {'enabled' if is_enabled else 'disabled'}")
return is_enabled
except Exception as e:
print(f"Error fetching feature flag '{flag_key}': {str(e)}")
raise e
# Usage example
try:
flag_enabled = handle_feature_flag(client, 'new-feature', 'user-123')
if flag_enabled:
# Implement new feature logic
else:
# Implement old feature logic
except Exception as e:
# Handle the error at a higher level

Local evaluation

Evaluating feature flags requires making a request to PostHog for each flag. However, you can improve performance by evaluating flags locally. Instead of making a request for each flag, PostHog will periodically request and store feature flag definitions locally, enabling you to evaluate flags without making additional requests.

It is best practice to use local evaluation flags when possible, since this enables you to resolve flags faster and with fewer API calls.

For details on how to implement local evaluation, see our local evaluation guide.

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

Python
variant = posthog.get_feature_flag('experiment-feature-flag-key', 'user_distinct_id')
if variant == 'variant-name':
# Do something

It's also possible to run experiments without using feature flags.

LLM observability

Our Python SDK includes a built-in LLM observability feature. It enables you to capture LLM usage, performance, and more. Check out our observability docs for more details on setting it up.

Error tracking

You can autocapture exceptions by setting the enable_exception_autocapture argument to True when initializing the PostHog client.

Python
from posthog import Posthog
posthog = Posthog("<ph_project_api_key>", enable_exception_autocapture=True, ...)

You can also manually capture exceptions using the capture_exception method:

Python

Contexts automatically capture exceptions thrown inside them, unless disable it by passing capture_exceptions=False to new_context().

GeoIP properties

Before posthog-python v3.0, we added GeoIP properties to all incoming events by default. We also used these properties for feature flag evaluation, based on the IP address of the request. This isn't ideal since they are created based on your server IP address, rather than the user's, leading to incorrect location resolution.

As of posthog-python v3.0, the default now is to disregard the server IP, not add the GeoIP properties, and not use the values for feature flag evaluations.

You can go back to previous behaviour by doing setting the disable_geoip argument in your initialization to False:

Python
posthog = Posthog('api_key', disable_geoip=False)

The list of properties that this overrides:

  1. $geoip_city_name
  2. $geoip_country_name
  3. $geoip_country_code
  4. $geoip_continent_name
  5. $geoip_continent_code
  6. $geoip_postal_code
  7. $geoip_time_zone

You can also explicitly chose to enable or disable GeoIP for a single capture request like so:

Python
posthog.capture('test_event', disable_geoip=True|False)

Historical migrations

You can use the Python or Node SDK to run historical migrations of data into PostHog. To do so, set the historical_migration option to true when initializing the client.

from posthog import Posthog
from datetime import datetime
posthog = Posthog(
'<ph_project_api_key>',
host='https://us.i.posthog.com',
debug=True,
historical_migration=True
)
events = [
{
"event": "batched_event_name",
"properties": {
"distinct_id": "user_id",
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
}
},
{
"event": "batched_event_name",
"properties": {
"distinct_id": "used_id",
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
}
}
]
for event in events:
posthog.capture(
distinct_id=event["properties"]["distinct_id"],
event=event["event"],
properties=event["properties"],
timestamp=event["properties"]["timestamp"],
)

Serverless environments (Render/Lambda/...)

By default, the library buffers events before sending them to the capture endpoint, for better performance. This can lead to lost events in serverless environments, if the Python process is terminated by the platform before the buffer is fully flushed. To avoid this, you can either:

  • Ensure that posthog.flush() is called after processing every request by adding a middleware to your server. This allows posthog.capture() to remain asynchronous for better performance. posthog.flush() is blocking.
  • Enable the sync_mode option when initializing the client, so that all calls to posthog.capture() become synchronous.

Django

See our Django docs for how to set up PostHog in Django. Our library includes a contexts middleware that can automatically capture distinct IDs, session IDs, and other properties you can set up with tags.

Alternative name

As our open source project PostHog shares the same module name, we created a special posthoganalytics package, mostly for internal use to avoid module collision. It is the exact same.

Thank you

This library is largely based on the analytics-python package.

Questions? Ask Max AI.

It's easier than reading through 678 pages of documentation

Community questions

Was this page useful?

Next article

React

PostHog makes it easy to get data about traffic and usage of your React app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. This guide walks you through an example integration of PostHog using React and the posthog-js library . Installation Usage PostHog provider The React context provider makes it easy to access the posthog-js library in your app. The provider can either take an initialized client…

Read next article