AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/python.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

Python

Canonical URL: https://posthog.com/docs/libraries/python

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.i.posthog.com instead of https://us.i.posthog.com (ingestion host), and use https://eu.posthog.com instead of https://app.posthog.com (app host for links).

On this page

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

These docs cover version 7.x of the Python SDK, which requires Python 3.10 or higher. On Python 3.9? See supported versions.

Install with the wizard

Run this command in your project directory to add PostHog to your Python project. The wizard detects your framework, installs the SDK, and sets up your first events.

npx @posthog/wizard

Or set it up manually by following the rest of this guide.

Installation

pip install posthog

Upgrading to v6

Version 6.x of the PostHog Python SDK introduces a new contexts API and breaking changes. If you're upgrading from 5.x to 6.x, read the migration guide first to learn more.

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

from posthog import Posthog

posthog = Posthog('<ph_project_token>', host='https://us.i.posthog.com')

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

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

Use the asyncio client

The Python SDK includes an asyncio-native client in version 7.45.0 and later. Continue to use Posthog in synchronous apps. For an asyncio app, install the optional async dependencies:

pip install "posthog[async]>=7.45.0"

Import AsyncPosthog, the customer-facing name for AsyncClient. Both names provide the same async context manager and lifecycle methods. Keep one client for the lifetime of your app. For example, use a FastAPI lifespan handler:

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from posthog import AsyncPosthog

@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncPosthog(
        os.environ["POSTHOG_PROJECT_TOKEN"],
        host=os.environ["POSTHOG_HOST"],
        secret_key=os.environ.get("POSTHOG_FEATURE_FLAGS_SECURE_API_KEY"),
    ) as posthog:
        app.state.posthog = posthog
        yield

app = FastAPI(lifespan=lifespan)

Exiting the context calls shutdown(). This flushes buffered events, waits for in-flight operations, stops the workers, and closes the HTTP transport. If you don't use the context manager, call await posthog.shutdown() during app shutdown. await posthog.join() has the same effect.

Capture events without blocking the event loop

capture() queues an event and returns without waiting for a network request. Don't await it:

posthog.capture(
    "event_name",
    distinct_id="user-distinct-id",
    properties={"source": "fastapi"},
)

Use capture_immediate() when your code must wait for that event's delivery attempt:

capture_id = await posthog.capture_immediate(
    "event_name",
    distinct_id="user-distinct-id",
)

Evaluate feature flags

Await evaluate_flags() once, then use its snapshot with synchronous in-memory accessors. Pass the same snapshot to capture() to attach the exact values used for branching without another feature flag request:

flags = await posthog.evaluate_flags("user-distinct-id")

if flags.is_enabled("new-checkout"):
    # Show the new checkout
    pass

posthog.capture(
    "checkout started",
    distinct_id="user-distinct-id",
    flags=flags,
)

The snapshot provides synchronous is_enabled(), get_flag(), and get_flag_payload() accessors. The awaited evaluate_flags() call also accepts groups, person_properties, group_properties, disable_geoip, flag_keys, and device_id arguments.

Fetch remote config

Initialize the client with a server-side secret API key as secret_key, then await the remote config request:

config = await posthog.get_remote_config_payload("landing-page-config")

See Remote config for setup and security details.

Identifying users

Identifying users is required. Backend events need a distinct_id to associate events with the correct user.

In Python, you can do this through a context. All event captures in the same context will be tagged automatically with the correct distinct_id. Typically, you would set a fresh context and identify at the top of each route.

from posthog import new_context, identify_context, capture

@app.get("/foo")
def foo(current_user: User = Depends(get_current_user)):
    with new_context(): # Set context at the top of a route
        identify_context(current_user.id)
        capture("foo_viewed")
    return {"status": "ok"}

When possible, write a small piece of middleware that resolves your authenticated user, wrap a context around the request, and identifies it. Every capture() downstream is then attributed automatically. The SDK's Django middleware does this automatically and you can replicate it when using the plain Python SDK.

Capturing events

You can send custom events using capture:

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

Tip: You can define event schemas with typed properties and generate type-safe code using schema management.

Setting event properties

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

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:

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:

# 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:

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.

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:

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:

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.

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:

from posthog import new_context, tag

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:

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:

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. When linking backend events to frontend sessions, use the session ID from the frontend SDK (PostHog session IDs are UUIDv7 strings).

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

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. Configure tracing_headers for your backend hostname to add the session and distinct ID headers to browser requests automatically.

You need to extract the header in your request handler (if you're using our Django middleware integration, this happens automatically).

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:

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 fresh and capture_exceptions arguments as new_context and provides a handy way to mark a whole function as being in a new context. For example:

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:

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

To update properties on a group:

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

The examples in this section use the synchronous Posthog client. For AsyncPosthog, use the awaited feature flag example. The returned snapshot uses the same accessors.

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 two steps to implement feature flags in Python:

Step 1: Evaluate flags once

Call posthog.evaluate_flags() once for the user, then read values from the returned snapshot.

Boolean feature flags

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

Multivariate feature flags

flags = posthog.evaluate_flags("distinct_id_of_your_user")

enabled_variant = flags.get_flag("flag-key")

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 = flags.get_flag_payload("flag-key")

flags.get_flag() returns the variant string for multivariate flags, True for enabled boolean flags, False for disabled flags, and None when the flag wasn't returned by the evaluation.

Note: posthog.feature_enabled(), posthog.get_feature_flag(), posthog.get_feature_flag_payload(), and posthog.capture(send_feature_flags=True) still work during the migration period, but they're deprecated. Prefer posthog.evaluate_flags() for new code.

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: Pass the evaluated flags snapshot to capture()

Pass the same flags object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another /flags request.

flags = posthog.evaluate_flags("distinct_id_of_your_user")

if flags.is_enabled("flag-key"):
    # Do something differently for this user
    pass

posthog.capture(
    "event_name",
    distinct_id="distinct_id_of_your_user",
    flags=flags,
)

By default, this attaches every flag in the snapshot using $feature/<flag-key> properties and $active_feature_flags.

To reduce event property bloat, pass a filtered snapshot:

# Attach only flags accessed with is_enabled() or get_flag() before this call
posthog.capture(
    "event_name",
    distinct_id="distinct_id_of_your_user",
    flags=flags.only_accessed(),
)

# Attach only specific flags
posthog.capture(
    "event_name",
    distinct_id="distinct_id_of_your_user",
    flags=flags.only(["checkout-flow", "new-dashboard"]),
)

only_accessed() is order-dependent. If you call it before accessing any flags with is_enabled() or get_flag(), no feature flag properties are attached.

Method 2: Include the $feature/feature_flag_name property manually

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

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

Evaluating only specific flags

By default, posthog.evaluate_flags() evaluates every flag for the user. If you only need a few flags, pass flag_keys to request only those flags:

flags = posthog.evaluate_flags(
    "distinct_id_of_your_user",
    flag_keys=["checkout-flow", "new-dashboard"],
)

Sending $feature_flag_called events

Capturing $feature_flag_called events enables PostHog to know when a flag was accessed by a user and provide analytics and insights on the flag. With posthog.evaluate_flags(), the SDK sends this event when you call flags.is_enabled() or flags.get_flag() for a flag.

The SDK deduplicates these events per (distinct_id, flag, value) in a local cache. If you reinitialize the PostHog client, the cache resets and $feature_flag_called events may be sent again. PostHog handles duplicates, so duplicate $feature_flag_called events don't affect your analytics.

flags.get_flag_payload() doesn't send $feature_flag_called events and doesn't count as an access for only_accessed().

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