Mixpanel Python SDK

5.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mixpanel client, track an event, and update user profiles. Ensure your Mixpanel Project Token is set via an environment variable or directly in the code. For applications that terminate quickly (e.g., scripts, serverless functions), explicitly calling `mp.flush()` is crucial to ensure all queued events are sent before the process exits.

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.")

view raw JSON →