Mixpanel Python SDK
The official Mixpanel library for Python provides functionalities to track events, manage user profiles (People), and integrate with Mixpanel's feature flagging system. It is currently at version 5.1.0 and maintains an active release cadence, frequently adding new features and ensuring compatibility with modern Python versions.
Warnings
- breaking The `api_host` parameter for initializing the `Mixpanel` client was removed in v5.0.0. Use the `api_region` parameter (`'US'` or `'EU'`) instead to specify the data residency region.
- breaking Support for Python versions older than 3.9 was dropped in version 4.11.0. If you are on an older Python version, you must use a `mixpanel` library version less than 4.11.0.
- gotcha The `Mixpanel` client operates synchronously by default. In long-running applications or those handling high event volumes, consider using asynchronous processing or a separate queueing mechanism to avoid blocking your main application thread. Always call `mp.flush()` to ensure all buffered events are sent before your application exits.
- gotcha Versions prior to 4.10.1 were prone to 'connection reset by peer' errors, especially during long-running sessions or network instability. This issue was resolved in v4.10.1.
Install
-
pip install mixpanel
Imports
- Mixpanel
from mixpanel import Mixpanel
Quickstart
import os
from mixpanel import Mixpanel
# Replace with your Mixpanel Project Token from environment variable or direct string
MIXPANEL_TOKEN = os.environ.get('MIXPANEL_TOKEN', 'YOUR_MIXPANEL_PROJECT_TOKEN')
if not MIXPANEL_TOKEN or MIXPANEL_TOKEN == 'YOUR_MIXPANEL_PROJECT_TOKEN':
print("Warning: MIXPANEL_TOKEN not set. Using placeholder. Events will not be sent to Mixpanel.")
# Initialize the Mixpanel client
# For EU data residency, use api_region='EU'
mp = Mixpanel(MIXPANEL_TOKEN, api_region='US')
# Track an event
user_id = 'user123'
event_name = 'Signup Success'
properties = {'source': 'website', 'plan': 'premium'}
mp.track(user_id, event_name, properties)
print(f"Tracked event '{event_name}' for user '{user_id}'")
# Update user profile (People properties)
people_properties = {'$first_name': 'John', '$last_name': 'Doe', 'plan': 'premium'}
mp.people_set(user_id, people_properties)
print(f"Set people properties for user '{user_id}'")
# Increment a people property
mp.people_increment(user_id, {'Login Count': 1})
print(f"Incremented 'Login Count' for user '{user_id}'")
# For non-web applications, ensure events are flushed before exiting
mp.flush()
print("Mixpanel client flushed.")