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.
Common errors
-
MixpanelException("Cannot interpret Mixpanel server response: {0}".format(response.text))cause This error occurs when the Mixpanel Python SDK receives a server response it cannot parse, often due to validation errors in the event data (e.g., malformed properties, invalid values, or events with timestamps too far in the past).fixEnsure that your event properties are correctly formatted (e.g., proper JSON structure, valid data types) and that event timestamps are within Mixpanel's acceptance window (typically within the last 5 days for `track()`, use `import_data()` for older events). Check the `response.text` for specific server error messages. -
TypeError: Object of type DataFrame is not JSON serializable
cause This error occurs when attempting to pass a pandas DataFrame object (or other non-JSON-serializable Python objects) directly as event properties or user profile properties to Mixpanel methods like `track()` or `people_set()`. Mixpanel expects properties to be JSON-serializable types.fixConvert DataFrame columns or other complex objects to basic JSON-serializable types (strings, numbers, booleans, lists, dictionaries) before passing them to Mixpanel methods. For DataFrames, convert relevant data to a dictionary or list of dictionaries. -
ConnectionError: HTTPSConnectionPool(host='data.mixpanel.com', port=443): Max retries exceeded with url: / (Caused by : [Errno 54] Connection reset by peer)
cause This indicates a network connectivity issue or that the Mixpanel API endpoint is unreachable or experiencing problems, preventing the Python SDK from establishing or maintaining a connection.fixCheck your network connection and firewall settings. Verify Mixpanel's service status. If making many requests, implement retry logic with exponential backoff or use a `BufferedConsumer` to handle transient network issues and queue events. -
ModuleNotFoundError: No module named 'mixpanel'
cause This error occurs when the `mixpanel` Python library has not been installed in the current environment or Python cannot find the installed package.fixInstall the Mixpanel Python library using pip: `pip install mixpanel`. If already installed, ensure your Python environment (e.g., virtual environment) is activated and correctly configured. -
mixpanel.people.set() not updating existing profile
cause While not a direct Python error, this common problem arises when `people.set()` is called without first calling `identify()` with the correct `distinct_id` for the target user, or if an incorrect `distinct_id` is used, preventing the profile properties from being correctly associated and updated in Mixpanel.fixAlways call `mixpanel.identify(distinct_id)` before using `mixpanel.people.set(distinct_id, properties)` to ensure the profile properties are correctly linked to the user. Verify that the `distinct_id` used for `identify()` and `people.set()` consistently matches the user's identifier in Mixpanel.
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.
- breaking The `api_region` parameter for initializing the `Mixpanel` client was introduced in v5.0.0. Versions prior to v5.0.0 do not support `api_region` and will raise a `TypeError` if used.
Install
-
pip install mixpanel
Imports
- Mixpanel
import mixpanel; mixpanel.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.")