PostHog Python SDK

7.11.0 · active · verified Sun Apr 12

The official Python SDK for PostHog, enabling integration into any Python application for product analytics, feature flags, and session recording. It's actively maintained with frequent minor releases, often addressing specific framework integrations or new AI/LLM-related tracking features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the PostHog client, capture a custom event, and identify a user. It's crucial to call `posthoganalytics.flush()` in short-lived scripts to ensure events are sent before the program terminates. For long-running applications, `flush()` is handled automatically at intervals.

import os
import posthoganalytics

# Initialize PostHog client
posthoganalytics.init(
    os.environ.get('POSTHOG_API_KEY', 'phc_YOUR_API_KEY'),
    host=os.environ.get('POSTHOG_HOST', 'https://app.posthog.com')
)

# Capture an event
posthoganalytics.capture(
    'test-user-id',
    'my_event', 
    {'property_key': 'property_value'}
)

# Identify a user
posthoganalytics.identify(
    'test-user-id',
    {'email': 'test@example.com', 'name': 'Test User'}
)

# Ensure all events are sent before exiting
posthoganalytics.flush()
print('PostHog events captured and flushed.')

view raw JSON →