PostHog Python SDK

7.9.12 · active · verified Sun Mar 29

The PostHog Python SDK makes it easy to capture events, evaluate feature flags, track errors, and more in your Python applications. It supports event tracking, user identification, group analytics, and local evaluation for feature flags. The library is actively maintained, with frequent updates, and the current version is 7.9.12.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the PostHog client with environment variables, capture a custom event, and evaluate a feature flag. It also includes an important step for graceful shutdown to ensure all buffered events are sent.

import os
from posthog import Posthog

# Initialize PostHog client using environment variables for API key and host
# Replace 'your_project_api_key' and 'https://us.i.posthog.com' with your actual values
# or ensure POSTHOG_PROJECT_API_KEY and POSTHOG_HOST are set in your environment.
posthog = Posthog(
    project_api_key=os.environ.get('POSTHOG_PROJECT_API_KEY', 'your_project_api_key'),
    host=os.environ.get('POSTHOG_HOST', 'https://us.i.posthog.com')
)

# Capture a custom event
distinct_id = "user_123_unique_id" # A unique identifier for the user or entity

posthog.capture(
    distinct_id=distinct_id,
    event="user_signed_up",
    properties={
        "plan": "free",
        "signup_method": "email_password"
    }
)

# Evaluate a feature flag
is_new_feature_enabled = posthog.feature_enabled(
    'new-feature-flag-key',
    distinct_id # Feature flags usually require a distinct_id
)

if is_new_feature_enabled:
    print(f"New feature is enabled for {distinct_id}!")
else:
    print(f"New feature is NOT enabled for {distinct_id}.")

# In serverless environments or scripts, ensure events are flushed before exiting.
# For long-running applications (e.g., web servers), this is often handled automatically
# by background threads, but explicit shutdown is good practice for reliability.
posthog.shutdown()
print("PostHog client shut down and events flushed.")

view raw JSON →