PostHog Python SDK
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
- gotcha Failing to call `posthoganalytics.flush()` or `posthoganalytics.shutdown()` in short-lived scripts or before your application exits can lead to lost events. Events are buffered and only sent periodically or upon explicit flush/shutdown.
- gotcha Incorrect `POSTHOG_API_KEY` or `POSTHOG_HOST` configuration often leads to events being silently dropped, as the SDK will attempt to send data but fail to reach the correct PostHog instance.
- breaking In versions 7.10.1 and earlier, the `capture_exceptions` argument in the Django middleware (if used) was implicitly passed as a positional argument. In 7.10.2+, it is strictly expected as a keyword argument.
Install
-
pip install posthoganalytics
Imports
- posthoganalytics
import posthoganalytics
- Posthog
from posthoganalytics import Posthog
Quickstart
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.')