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.
pip install posthogVerified import paths — ran on the pinned version, not inferred.
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.
Migrate from `identify()` to `identify_context()` within a `new_context()` block. Update all `capture()` and `capture_exception()` calls to use keyword arguments for parameters like `distinct_id` and `event`.
Upgrade your Python environment to 3.10 or higher before upgrading to PostHog SDK version 7.0.0+.
Ensure `posthog.shutdown()` is explicitly called before the function exits, or initialize the client with `sync_mode=True` (e.g., `posthog = Posthog(..., sync_mode=True)`) to send events synchronously.
For true asynchronous use cases, consider existing asynchronous forks (e.g., `posthog-async` - note this is a separate package) or specific async integrations provided by PostHog (e.g., for LLM clients). The core client's `capture()` is non-blocking but not `awaitable`.
For production environments, consider setting up a reverse proxy to circumvent ad blockers and ensure more reliable data ingestion.
Always use environment variables (e.g., `os.environ.get('POSTHOG_PROJECT_API_KEY')`) to securely pass your API key and host to the PostHog client upon initialization.Ensure the `project_api_key` used to initialize the PostHog client is correct and active for your PostHog project. Verify it against your project settings in PostHog. Double-check for typos and ensure your `host` configuration is also correct.
Install the PostHog Python library using pip: `pip install posthog`
Rename your local file or directory (e.g., `posthog.py` to `my_posthog_utils.py`) to avoid the name collision with the official PostHog package.
Verify that the `api_key` and `host` (if self-hosting) passed to `posthog.init()` are correct and match your PostHog project settings. Ensure environment variables are loaded correctly if used.