### Basic Mixpanel Setup with Token Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Initialize the Mixpanel client using only your project token. This is the simplest way to get started. ```python from mixpanel import Mixpanel mp = Mixpanel("YOUR_TOKEN") mp.track("user123", "event_name") ``` -------------------------------- ### Quick Start: Initialize and Use Mixpanel Provider Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Initialize the MixpanelProvider with a project token for local evaluation and register it with the OpenFeature API. Then, get a client to evaluate boolean flags. ```python from mixpanel_openfeature import MixpanelProvider from mixpanel.flags.types import LocalFlagsConfig from openfeature import api # 1. Create and register the provider with local evaluation provider = MixpanelProvider.from_local_config( "YOUR_PROJECT_TOKEN", LocalFlagsConfig(token="YOUR_PROJECT_TOKEN"), ) api.set_provider(provider) # 2. Get a client and evaluate flags client = api.get_client() show_new_feature = client.get_boolean_value("new-feature-flag", False) if show_new_feature: print("New feature is enabled!") ``` -------------------------------- ### Install Test and Developer Environment Source: https://github.com/mixpanel/mixpanel-python/blob/master/BUILD.rst Installs the package in editable mode along with necessary modules for testing and development. ```bash pip install -e .[test,dev] ``` -------------------------------- ### Install OpenFeature Python SDK Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Install the OpenFeature Python SDK, which is required to use the Mixpanel provider. ```bash pip install openfeature-sdk ``` -------------------------------- ### Install Mixpanel OpenFeature Provider Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Install the Mixpanel OpenFeature provider package using pip. ```bash pip install mixpanel-openfeature ``` -------------------------------- ### Complete Production Mixpanel Setup Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md A comprehensive setup for production environments, loading configurations from environment variables and combining service account credentials, buffered consumer, and local feature flags. ```python import os from mixpanel import Mixpanel, BufferedConsumer, ServiceAccountCredentials from mixpanel.flags.types import LocalFlagsConfig # Load from environment token = os.getenv("MIXPANEL_TOKEN") sa_username = os.getenv("SERVICE_ACCOUNT_USERNAME") sa_secret = os.getenv("SERVICE_ACCOUNT_SECRET") sa_project_id = os.getenv("SERVICE_ACCOUNT_PROJECT_ID") # Create credentials and consumer credentials = ServiceAccountCredentials( username=sa_username, secret=sa_secret, project_id=sa_project_id ) consumer = BufferedConsumer( max_size=50, credentials=credentials, retry_limit=5, retry_backoff_factor=0.5, request_timeout=30 ) # Create client with all configurations mp = Mixpanel( token, consumer=consumer, credentials=credentials, local_flags_config=LocalFlagsConfig( polling_interval_in_seconds=120, enable_polling=True ) ) # Use the client mp.local_flags.start_polling_for_definitions() mp.track("user123", "signup", {"plan": "premium"}) mp.people_set("user123", {"$first_name": "John", "plan": "premium"}) # Always flush before exit consumer.flush() ``` -------------------------------- ### Mixpanel Setup with Local Feature Flags Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Configure and enable local feature flags. This allows for faster flag evaluation by fetching flag definitions periodically. Ensure polling is enabled and start the polling process. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig config = LocalFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10, enable_polling=True, polling_interval_in_seconds=60 ) mp = Mixpanel("YOUR_TOKEN", local_flags_config=config) mp.local_flags.start_polling_for_definitions() # Evaluate flags context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) ``` -------------------------------- ### Install Mixpanel Python Library Source: https://github.com/mixpanel/mixpanel-python/blob/master/README.md Install the library using pip. This is the first step to integrating Mixpanel into your Python application. ```bash pip install mixpanel ``` -------------------------------- ### Synchronous Context Manager for Mixpanel Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Use the Mixpanel client as a synchronous context manager for automatic resource cleanup. This example demonstrates tracking an event and getting a feature flag variant. ```python # Synchronous context manager with Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) as mp: mp.track("user123", "event_name") variant = mp.local_flags.get_variant_value("flag", fallback=False, context={}) ``` -------------------------------- ### Mixpanel Setup with Service Account Credentials Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Configure the Mixpanel client using service account credentials for authentication. This is recommended for server-to-server integrations. ```python from mixpanel import Mixpanel, ServiceAccountCredentials credentials = ServiceAccountCredentials( username="service-account-username", secret="service-account-secret", project_id="123456" ) mp = Mixpanel("YOUR_TOKEN", credentials=credentials) ``` -------------------------------- ### Asynchronous Context Manager for Mixpanel Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Use the Mixpanel client as an asynchronous context manager for automatic resource cleanup. This example demonstrates tracking an event and asynchronously getting a feature flag variant. ```python # Asynchronous context manager async with Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) as mp: mp.track("user123", "event_name") variant = await mp.local_flags.aget_variant_value("flag", fallback=False, context={}) ``` -------------------------------- ### Using Synchronous and Asynchronous Context Managers Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Demonstrates how to use LocalFeatureFlagsProvider with both synchronous and asynchronous context managers. Ensure to start and stop polling appropriately within the context. ```python with Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) as mp: mp.local_flags.start_polling_for_definitions() variant = mp.local_flags.get_variant_value("flag", fallback=False, context={}) # Polling stopped and resources cleaned up on exit ``` ```python async with Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) as mp: await mp.local_flags.astart_polling_for_definitions() variant = await mp.local_flags.aget_variant_value("flag", fallback=False, context={}) # Polling stopped and resources cleaned up on exit ``` -------------------------------- ### Documentation Structure Overview Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/START_HERE.md Illustrates the hierarchical organization of the Mixpanel Python SDK documentation, showing how this starting file relates to the main README and other detailed reference sections. ```markdown # Mixpanel Python SDK (v5.1.0) - Technical Reference **Start here** for navigation and overview. ## 📖 Documentation Structure ``` START_HERE.md (you are here) ↓ README.md (navigation guide) ↓ Choose your path: ├─ REFERENCE_INDEX.md (complete index & quick reference) ├─ api-reference/ (detailed class documentation) ├─ configuration.md (all options) ├─ types.md (type definitions) └─ errors.md (error handling) ``` --- ## 🎯 Quick Navigation by Task ### I want to track events → [Mixpanel.track() method](api-reference/Mixpanel.md#track) ### I want to manage user profiles → [People Analytics methods](api-reference/Mixpanel.md#people-analytics-methods) ### I want to manage group profiles → [Group Analytics methods](api-reference/Mixpanel.md#group-analytics-methods) ### I want to use feature flags (client-side) → [LocalFeatureFlagsProvider](api-reference/LocalFeatureFlagsProvider.md) ### I want to use feature flags (server-side) → [RemoteFeatureFlagsProvider](api-reference/RemoteFeatureFlagsProvider.md) ### I want to batch events → [BufferedConsumer](api-reference/BufferedConsumer.md) ### I want to see all configuration options → [configuration.md](configuration.md) ### I want error handling examples → [errors.md](errors.md) ### I want complete integration examples → [MixpanelIntegration.md](api-reference/MixpanelIntegration.md) --- ## 📚 All Documentation Files ### Entry Points - **README.md** — Navigation guide and complete file index - **REFERENCE_INDEX.md** — Comprehensive reference with quick lookup tables - **START_HERE.md** — This file ### Core Documentation - **api-reference/Mixpanel.md** — Main Mixpanel class (876 lines) - **api-reference/Consumer.md** — Direct HTTP consumer - **api-reference/BufferedConsumer.md** — Batching consumer - **api-reference/ServiceAccountCredentials.md** — Service account authentication - **api-reference/LocalFeatureFlagsProvider.md** — Client-side flags - **api-reference/RemoteFeatureFlagsProvider.md** — Server-side flags - **api-reference/UtilityFunctions.md** — Utilities and helpers - **api-reference/MixpanelIntegration.md** — Integration patterns (548 lines) ### Reference Guides - **configuration.md** — All constructor options and setup patterns - **types.md** — Type definitions, models, and exceptions - **errors.md** — Error conditions and handling guide ``` -------------------------------- ### Instantiate RemoteFeatureFlagsProvider Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Example of how to instantiate the Mixpanel client with remote flags configuration. This is the typical way to set up the RemoteFeatureFlagsProvider, usually accessed via `mp.remote_flags`. ```python from mixpanel import Mixpanel from mixpanel.flags.types import RemoteFlagsConfig config = RemoteFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10 ) mp = Mixpanel("YOUR_TOKEN", remote_flags_config=config) # Access via mp.remote_flags ``` -------------------------------- ### Mixpanel Setup with Both Local and Remote Flags Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Configure both local and remote feature flags. This setup attempts to use local flags first for performance, falling back to remote flags if local flags are not ready. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig, RemoteFlagsConfig mp = Mixpanel( "YOUR_TOKEN", local_flags_config=LocalFlagsConfig(), remote_flags_config=RemoteFlagsConfig() ) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} # Try local flag first (faster) if mp.local_flags.are_flags_ready(): variant = mp.local_flags.get_variant_value("flag", None, context) else: # Fall back to remote if local not ready variant = mp.remote_flags.get_variant_value("flag", None, context) ``` -------------------------------- ### Start Polling for Flag Definitions Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Fetches flag definitions and starts background polling if enabled in the configuration. This method can only be called once. ```python mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig(enable_polling=True)) mp.local_flags.start_polling_for_definitions() # Flags are now available for evaluation context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) ``` -------------------------------- ### astart_polling_for_definitions Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Asynchronously fetches flag definitions and starts async polling if enabled. This is the asynchronous counterpart to `start_polling_for_definitions`. ```APIDOC ## astart_polling_for_definitions() ### Description Asynchronously fetches flag definitions and starts an asyncio polling task if enabled. This method can only be called once per provider instance. ### Method `async def astart_polling_for_definitions(self) -> None` ### Behavior - Asynchronously fetches flag definitions. - If `config.enable_polling` is True, creates an asyncio task for polling. - The task polls at `config.polling_interval_in_seconds` intervals. - Can only be called once per provider instance. ### Example ```python import asyncio from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig async def main(): mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig(enable_polling=True)) await mp.local_flags.astart_polling_for_definitions() context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) asyncio.run(main()) ``` ``` -------------------------------- ### Service Account Authentication Setup Source: https://github.com/mixpanel/mixpanel-python/blob/master/README.md Configure Mixpanel with service account credentials for secure server-to-server authentication. This replaces API secrets for enhanced security. ```python from mixpanel import Mixpanel, ServiceAccountCredentials # Create credentials object # Service accounts replace api_key/api_secret for authentication credentials = ServiceAccountCredentials( username='YOUR_SERVICE_ACCOUNT_USERNAME', secret='YOUR_SERVICE_ACCOUNT_SECRET', project_id='YOUR_PROJECT_ID' ) # Token identifies the project and is used for event tracking # Credentials are used for endpoints that require authentication mp = Mixpanel(YOUR_TOKEN, credentials=credentials) # Event tracking operations use the token (sent in payload) mp.track(DISTINCT_ID, 'button clicked', {'color': 'blue'}) mp.people_set(DISTINCT_ID, {'$first_name': 'John'}) ``` -------------------------------- ### Mixpanel Setup with Custom Timeouts and Retries Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Configure the Consumer with custom API host, request timeout, and retry settings. This allows fine-tuning network behavior for reliability. ```python from mixpanel import Mixpanel, Consumer consumer = Consumer( api_host="api.mixpanel.com", request_timeout=30, retry_limit=5, retry_backoff_factor=0.5 ) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` -------------------------------- ### Asynchronously Start Polling for Flag Definitions Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Asynchronously fetches flag definitions and starts async polling if enabled. This method can only be called once per provider instance. ```python import asyncio from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig async def main(): mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig(enable_polling=True)) await mp.local_flags.astart_polling_for_definitions() context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) asyncio.run(main()) ``` -------------------------------- ### start_polling_for_definitions Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Fetches flag definitions and starts background polling for updates if enabled. This method can only be called once. ```APIDOC ## start_polling_for_definitions() ### Description Fetches flag definitions and starts a background polling thread if enabled in the configuration. Subsequent calls will be ignored. ### Method `start_polling_for_definitions(self) -> None` ### Behavior - Immediately fetches flag definitions from the API. - If `config.enable_polling` is True, starts a background daemon thread. - The thread polls for updates at `config.polling_interval_in_seconds` intervals. - Can only be called once; subsequent calls log a warning. ### Example ```python mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig(enable_polling=True)) mp.local_flags.start_polling_for_definitions() # Flags are now available for evaluation context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) ``` ``` -------------------------------- ### Mixpanel Setup with Remote Feature Flags Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Configure and enable remote feature flags. Flag evaluation is done by sending requests to the Mixpanel API for each evaluation. ```python from mixpanel import Mixpanel from mixpanel.flags.types import RemoteFlagsConfig config = RemoteFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10 ) mp = Mixpanel("YOUR_TOKEN", remote_flags_config=config) # Evaluate flags context = {"distinct_id": "user123"} is_enabled = mp.remote_flags.is_enabled("my-flag", context) ``` -------------------------------- ### Enable Local Feature Flags Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/README.md Initialize Mixpanel with local feature flags and start polling for definitions. Check if a feature is enabled for a given context. ```python from mixpanel.flags.types import LocalFlagsConfig mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} if mp.local_flags.is_enabled("new-feature", context): # Show feature pass ``` -------------------------------- ### Mixpanel Setup with Custom JSON Serializer Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Provide a custom serializer, such as DatetimeSerializer, to handle specific data types like datetime objects when tracking events. ```python from mixpanel import Mixpanel, DatetimeSerializer import datetime mp = Mixpanel("YOUR_TOKEN", serializer=DatetimeSerializer) mp.track("user123", "event_name", { "timestamp": datetime.datetime.now(), "price": 19.99 }) ``` -------------------------------- ### Initialize MixpanelProvider for Local Evaluation Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Use this method for server-side applications to minimize latency by evaluating flags locally using cached definitions. It automatically starts polling for flag definitions in the background. ```python from mixpanel_openfeature import MixpanelProvider from mixpanel.flags.types import LocalFlagsConfig provider = MixpanelProvider.from_local_config( "YOUR_PROJECT_TOKEN", LocalFlagsConfig(token="YOUR_PROJECT_TOKEN"), ) ``` -------------------------------- ### Configure and Start Polling for Local Feature Flags Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Configure local feature flags with polling enabled to automatically fetch flag definitions. Ensure flags are ready before evaluation by checking `are_flags_ready()`. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig # Configure local flags with polling config = LocalFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10, enable_polling=True, polling_interval_in_seconds=60 ) mp = Mixpanel("YOUR_TOKEN", local_flags_config=config) # Start polling mp.local_flags.start_polling_for_definitions() # Wait for flags to be ready import time while not mp.local_flags.are_flags_ready(): time.sleep(0.1) # Evaluate flags context = { "distinct_id": "user123", "custom_properties": {"plan": "premium"} } is_enabled = mp.local_flags.is_enabled("premium-feature", context) ``` -------------------------------- ### Context Dictionary for Feature Flag Evaluation Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Provides an example of a context dictionary required for evaluating feature flags. It must include 'distinct_id' and any flag-specific context properties, with optional 'custom_properties'. ```python context = { "distinct_id": "user123", "user_id": "user123", # Flag context property "custom_properties": { "plan": "premium", "country": "US", "created_date": "2024-01-01" } } variant = mp.local_flags.get_variant_value("premium-feature", False, context) ``` -------------------------------- ### Complete Mixpanel Application Initialization and Usage Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Demonstrates initializing the Mixpanel SDK with optional service account credentials, a buffered consumer, and local feature flags. Includes tracking events, setting user properties, and evaluating feature flags. ```python import os import logging from mixpanel import Mixpanel, BufferedConsumer, ServiceAccountCredentials from mixpanel.flags.types import LocalFlagsConfig # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize Mixpanel with all features def init_mixpanel(): token = os.getenv("MIXPANEL_TOKEN") # Optional service account credentials = None sa_username = os.getenv("SERVICE_ACCOUNT_USERNAME") sa_secret = os.getenv("SERVICE_ACCOUNT_SECRET") sa_project_id = os.getenv("SERVICE_ACCOUNT_PROJECT_ID") if all([sa_username, sa_secret, sa_project_id]): credentials = ServiceAccountCredentials( username=sa_username, secret=sa_secret, project_id=sa_project_id ) # Use buffered consumer for batch sending consumer = BufferedConsumer( max_size=50, credentials=credentials, retry_limit=5 ) # Initialize with local flags mp = Mixpanel( token, consumer=consumer, credentials=credentials, local_flags_config=LocalFlagsConfig( enable_polling=True, polling_interval_in_seconds=60 ) ) # Start polling for flag updates try: mp.local_flags.start_polling_for_definitions() except Exception as e: logger.warning(f"Could not start flag polling: {e}") return mp, consumer # Use in application try: mp, consumer = init_mixpanel() # Track event try: mp.track("user123", "signup", { "email": "user@example.com", "plan": "premium" }) except Exception as e: logger.error(f"Failed to track event: {e}") # Set user properties try: mp.people_set("user123", { "$first_name": "John", "$email": "user@example.com" }) except Exception as e: logger.error(f"Failed to set user properties: {e}") # Check feature flag try: context = {"distinct_id": "user123"} if mp.local_flags.is_enabled("new-feature", context): # Enable new feature pass except Exception as e: logger.error(f"Failed to evaluate flag: {e}") finally: # Ensure all events are sent before exit try: consumer.flush() logger.info("All events flushed successfully") except Exception as e: logger.error(f"Failed to flush events: {e}") ``` -------------------------------- ### Initialize Consumer with Service Account Credentials Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Consumer.md Set up the Consumer using service account credentials for authentication, primarily for the /import endpoint. Ensure you have the correct username, secret, and project ID. ```python from mixpanel import ServiceAccountCredentials credentials = ServiceAccountCredentials( username="username", secret="secret", project_id="123456" ) consumer = Consumer(credentials=credentials) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` -------------------------------- ### Initialize Mixpanel Client Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/REFERENCE_INDEX.md Instantiate the Mixpanel client with your project token. This is the first step for any integration. ```python from mixpanel import Mixpanel mp = Mixpanel("YOUR_TOKEN") ``` -------------------------------- ### Initialize Mixpanel with Different Configurations Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Demonstrates how to initialize the Mixpanel client with a basic token, service account credentials, local feature flags, or a custom consumer. Choose the initialization method based on your authentication and delivery needs. ```python from mixpanel import Mixpanel, ServiceAccountCredentials # Basic initialization with token mp = Mixpanel("YOUR_TOKEN") ``` ```python credentials = ServiceAccountCredentials( username="service-account-username", secret="service-account-secret", project_id="123456" ) mp = Mixpanel("YOUR_TOKEN", credentials=credentials) ``` ```python from mixpanel.flags.types import LocalFlagsConfig mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) ``` ```python from mixpanel import BufferedConsumer consumer = BufferedConsumer(max_size=50) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` -------------------------------- ### Initialize Mixpanel with Service Account Credentials Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/configuration.md Use environment variables to securely load service account credentials and initialize the Mixpanel client. Ensure MIXPANEL_TOKEN, SERVICE_ACCOUNT_USERNAME, SERVICE_ACCOUNT_SECRET, and SERVICE_ACCOUNT_PROJECT_ID are set. ```python import os from mixpanel import Mixpanel, ServiceAccountCredentials token = os.getenv("MIXPANEL_TOKEN") username = os.getenv("SERVICE_ACCOUNT_USERNAME") secret = os.getenv("SERVICE_ACCOUNT_SECRET") project_id = os.getenv("SERVICE_ACCOUNT_PROJECT_ID") credentials = ServiceAccountCredentials( username=username, secret=secret, project_id=project_id ) mp = Mixpanel(token, credentials=credentials) ``` -------------------------------- ### Build Documentation Source: https://github.com/mixpanel/mixpanel-python/blob/master/BUILD.rst Generates HTML documentation from Sphinx source files. ```bash python -m sphinx -b html docs docs/_build/html ``` -------------------------------- ### Get Flag Definitions Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/GENERATION_SUMMARY.txt Retrieve definitions for feature flags. ```APIDOC ## GET /flags/definitions (flag definitions) ### Description Retrieve definitions for feature flags. ### Method GET ### Endpoint /flags/definitions ### Parameters #### Query Parameters - **filter** (string) - Optional - A filter to apply to the flag definitions. ### Response #### Success Response (200) - **definitions** (array) - A list of flag definitions. #### Response Example ```json { "definitions": [ { "name": "new_feature", "defaultValue": false } ] } ``` ``` -------------------------------- ### Initialize MixpanelProvider with Existing Mixpanel Instance Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Integrate the provider with an already configured Mixpanel instance. The provider wraps the existing flags provider, and `provider.mixpanel` will be `None` as the instance is not owned by the provider. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig from mixpanel_openfeature import MixpanelProvider # Your existing Mixpanel instance mp = Mixpanel("YOUR_PROJECT_TOKEN", local_flags_config=LocalFlagsConfig(token="YOUR_PROJECT_TOKEN")) local_flags = mp.local_flags local_flags.start_polling_for_definitions() # Wrap the existing flags provider with OpenFeature provider = MixpanelProvider(local_flags) ``` -------------------------------- ### Build the OpenFeature Provider Package Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/RELEASE.md Builds the Python package for the OpenFeature provider. Ensure you are in the `openfeature-provider` directory before running. ```bash cd openfeature-provider python -m build ``` -------------------------------- ### Handle MixpanelException During Event Tracking Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/types.md Example of how to catch MixpanelException when tracking events. This is useful for gracefully handling potential sending failures. ```python from mixpanel import Mixpanel, MixpanelException mp = Mixpanel("YOUR_TOKEN") try: mp.track("user123", "event_name") except MixpanelException as e: print(f"Failed to track event: {e}") ``` -------------------------------- ### Verify Built Artifacts Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/RELEASE.md Lists the contents of the `dist/` directory to verify that the wheel and source distribution files have been created correctly. ```bash ls dist/ # Should show: mixpanel_openfeature--py3-none-any.whl # mixpanel_openfeature-.tar.gz ``` -------------------------------- ### Set Group Properties Once Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Use `group_set_once` to set properties on a group profile only if they have not been set previously. This is useful for initial setup or immutable properties. ```python mp.group_set_once("company", "acme-corp", {"founded": "2010"}) ``` -------------------------------- ### Get Remote Feature Flags Provider Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Access the remote feature flags provider. Ensure the Mixpanel client is initialized with `remote_flags_config` to use this. ```python from mixpanel.flags.types import RemoteFlagsConfig mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} is_enabled = mp.remote_flags.is_enabled("my-flag", context) ``` -------------------------------- ### Get Local Feature Flags Provider Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Access the local feature flags provider. Ensure the Mixpanel client is initialized with `local_flags_config` to use this. ```python from mixpanel.flags.types import LocalFlagsConfig mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) context = {"distinct_id": "user123"} is_enabled = mp.local_flags.is_enabled("my-flag", context) ``` -------------------------------- ### Consumer Constructor Parameters Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/COMPLETION_REPORT.md Configuration options for the Consumer constructor. ```APIDOC ## Consumer Configuration ### Constructor Parameters - (10 parameters available for configuring the Consumer. Specific parameter names are not detailed in the source.) ``` -------------------------------- ### BufferedConsumer Constructor Parameters Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/COMPLETION_REPORT.md Configuration options for the BufferedConsumer constructor. ```APIDOC ## BufferedConsumer Configuration ### Constructor Parameters - (11 parameters available for configuring the BufferedConsumer. Specific parameter names are not detailed in the source.) ``` -------------------------------- ### Get Basic Boolean Flag Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Retrieve a boolean feature flag's value with a specified default. Use this for simple on/off feature toggles. ```python client = api.get_client() # Get a boolean flag with a default value is_feature_enabled = client.get_boolean_value("my-feature", False) if is_feature_enabled: # Show the new feature pass ``` -------------------------------- ### Publish Docs to GitHub Pages Source: https://github.com/mixpanel/mixpanel-python/blob/master/BUILD.rst Imports and publishes the built HTML documentation to GitHub Pages. ```bash python -m ghp_import -n -p docs/_build/html ``` -------------------------------- ### Getting Variant Values Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Retrieve the specific variant value for a feature flag, with an option to provide a fallback value if the flag is not enabled or has no assigned variant. ```APIDOC ## Getting Variant Values ### Description Retrieves the variant value for a feature flag, providing a fallback if necessary. ### Method Signature `mp.remote_flags.get_variant_value(flag_name: str, fallback_value: any, context: dict) -> any` ### Parameters * **flag_name** (str) - The name of the feature flag. * **fallback_value** (any) - The value to return if the flag is not enabled or no variant is found. * **context** (dict) - A dictionary containing user properties and traits for flag evaluation. Must include at least `"distinct_id"`. ### Request Example ```python context = {"distinct_id": "user123"} button_color = mp.remote_flags.get_variant_value("button-color", fallback_value="blue", context=context) ``` ### Response * **any** - The assigned variant value for the flag, or the `fallback_value`. ``` -------------------------------- ### Publish to PyPI Source: https://github.com/mixpanel/mixpanel-python/blob/master/BUILD.rst Builds the package and uploads it to the Python Package Index. ```bash python -m build ``` ```bash python -m twine upload dist/* ``` -------------------------------- ### Configure PyPI Credentials in ~/.pypirc Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/RELEASE.md An alternative method to uploading to PyPI is by configuring your credentials in the `~/.pypirc` file. This avoids interactive prompts during the upload process. ```ini [pypi] username = __token__ password = pypi- ``` -------------------------------- ### Evaluate Local Feature Flag Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/REFERENCE_INDEX.md Check if a local feature flag is enabled for a given context. Requires initializing Mixpanel with `LocalFlagsConfig` and starting definition polling. ```python from mixpanel.flags.types import LocalFlagsConfig mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} if mp.local_flags.is_enabled("new-feature", context): # Enable feature pass ``` -------------------------------- ### Initialize Mixpanel with Local Flags Configuration Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/types.md Instantiate Mixpanel with a LocalFlagsConfig object for client-side flag management, including polling settings. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig config = LocalFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10, enable_polling=True, polling_interval_in_seconds=60 ) mp = Mixpanel("YOUR_TOKEN", local_flags_config=config) ``` -------------------------------- ### Mixpanel Constructor Parameters Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/COMPLETION_REPORT.md Configuration options for the Mixpanel constructor. ```APIDOC ## Mixpanel Configuration ### Constructor Parameters - (6 parameters available for configuring the Mixpanel client. Specific parameter names are not detailed in the source.) ``` -------------------------------- ### Get Feature Flag Variant with Fallback Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/types.md Use SelectedVariant to provide a fallback value when retrieving a feature flag variant, ensuring a default is always available. ```python from mixpanel.flags.types import SelectedVariant fallback = SelectedVariant( variant_key=None, variant_value=False, experiment_id=None, is_experiment_active=None, is_qa_tester=None ) mp.local_flags.get_variant("my-flag", fallback, context) ``` -------------------------------- ### Initialize Mixpanel with Remote Flags Configuration Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/types.md Create a Mixpanel instance using RemoteFlagsConfig for server-side flag management, specifying API host and timeout. ```python from mixpanel import Mixpanel from mixpanel.flags.types import RemoteFlagsConfig config = RemoteFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10 ) mp = Mixpanel("YOUR_TOKEN", remote_flags_config=config) ``` -------------------------------- ### Upload Package to PyPI Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/RELEASE.md Uploads the built distribution files to PyPI using twine. You will be prompted for your PyPI credentials. ```bash python -m twine upload dist/* ``` -------------------------------- ### Initialize Consumer with Defaults Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Consumer.md Instantiate the Consumer class using default settings for API endpoints and retry behavior. This is suitable for basic usage. ```python from mixpanel import Consumer, Mixpanel # Basic consumer with defaults consumer = Consumer() mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` -------------------------------- ### Initialize MixpanelProvider for Remote Evaluation Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Choose this method when real-time flag values are critical and network latency is acceptable, as it makes a request to Mixpanel's servers for each evaluation. ```python from mixpanel_openfeature import MixpanelProvider from mixpanel.flags.types import RemoteFlagsConfig provider = MixpanelProvider.from_remote_config( "YOUR_PROJECT_TOKEN", RemoteFlagsConfig(token="YOUR_PROJECT_TOKEN"), ) ``` -------------------------------- ### Validate Service Account Credentials Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Handles potential TypeError or ValueError exceptions when initializing ServiceAccountCredentials. Use this to catch invalid credential formats or missing required parameters during setup. ```python from mixpanel import ServiceAccountCredentials try: credentials = ServiceAccountCredentials( username=username_from_env, secret=secret_from_env, project_id=project_id_from_env ) except (TypeError, ValueError) as e: print(f"Invalid credentials: {e}") # Handle configuration error ``` -------------------------------- ### Custom Datetime Serialization Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Implement a custom JSON encoder to define a specific format for datetime objects when serializing event data. This example uses ISO format with timezone. ```python import json import datetime class CustomDateSerializer(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.isoformat() # ISO format with timezone return super().default(obj) mp = Mixpanel("YOUR_TOKEN", serializer=CustomDateSerializer) ``` -------------------------------- ### Get All Feature Flag Variants for a User Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Use `get_all_variants` to fetch all feature flag variants for a user in a single server call. Note that exposure events are not automatically tracked with this method. ```python mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} all_variants = mp.remote_flags.get_all_variants(context) if all_variants: for flag_key, variant in all_variants.items(): print(f"{flag_key}: {variant.variant_value}") ``` -------------------------------- ### Prepare Common Query Parameters for API Requests Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/UtilityFunctions.md Builds common query parameters required for feature flag API requests. Include the project token, SDK version, and optionally a service account project ID. ```python from mixpanel.flags.utils import prepare_common_query_params params = prepare_common_query_params( token="YOUR_TOKEN", sdk_version="5.1.0", project_id="123456" ) # Output: { # "mp_lib": "python", # "lib_version": "5.1.0", # "token": "YOUR_TOKEN", # "project_id": "123456" # } ``` -------------------------------- ### Queueing Events with BufferedConsumer Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/BufferedConsumer.md Demonstrates how to use BufferedConsumer to queue events. Messages are buffered until the consumer's max_size is reached, at which point it automatically flushes. ```python consumer = BufferedConsumer(max_size=20) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) # These messages are buffered (no network traffic yet) for i in range(15): mp.track("user123", "event_" + str(i)) # This 16th message causes buffer to stay under limit mp.track("user123", "event_15") # This 20th message triggers auto-flush when buffer size reaches 20 for i in range(16, 21): mp.track("user123", "event_" + str(i)) ``` -------------------------------- ### Initialize BufferedConsumer Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/BufferedConsumer.md Instantiate a BufferedConsumer with default or custom parameters. Call `flush()` before program exit to send all buffered messages. ```python from mixpanel import Mixpanel, BufferedConsumer, ServiceAccountCredentials # Basic buffered consumer consumer = BufferedConsumer(max_size=50) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) # Track multiple events for i in range(100): mp.track("user123", "event_name", {"index": i}) # Flush any remaining buffered messages before exit consumer.flush() # With service account credentials credentials = ServiceAccountCredentials( username="username", secret="secret", project_id="123456" ) consumer = BufferedConsumer(max_size=50, credentials=credentials) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` -------------------------------- ### Get All Variants for a User Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Efficiently retrieve all variants a user qualifies for in a single call using `get_all_variants`. Note that exposure events are not tracked automatically and must be reported manually using `track_exposure_event`. ```python mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} all_variants = mp.local_flags.get_all_variants(context) for flag_key, variant in all_variants.items(): print(f"{flag_key}: {variant.variant_value}") mp.local_flags.track_exposure_event(flag_key, variant, context) ``` -------------------------------- ### Get Complete Variant Object Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Use `get_variant` to obtain the full `SelectedVariant` object, which includes the variant key, value, and experiment metadata. You can control exposure event tracking with the `report_exposure` parameter. ```python from mixpanel.flags.types import SelectedVariant mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} fallback = SelectedVariant(variant_key=None, variant_value="control") variant = mp.local_flags.get_variant( "experiment-flag", fallback, context, report_exposure=True ) print(variant.variant_key) # e.g., "variant_a" print(variant.variant_value) # e.g., {"text": "New UI"} ``` -------------------------------- ### ServiceAccountCredentials Constructor Parameters Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/COMPLETION_REPORT.md Configuration options for ServiceAccountCredentials. ```APIDOC ## ServiceAccountCredentials Configuration ### Constructor Parameters - (3 parameters available. Specific parameter names are not detailed in the source.) ``` -------------------------------- ### Get Full Flag Resolution Details Source: https://github.com/mixpanel/mixpanel-python/blob/master/openfeature-provider/README.md Retrieve detailed information about a flag evaluation, including the resolved value, variant, reason for the resolution, and any error codes. Useful for debugging and understanding flag behavior. ```python client = api.get_client() details = client.get_boolean_details("my-feature", False) print(details.value) # The resolved value print(details.variant) # The variant key from Mixpanel print(details.reason) # Why this value was returned print(details.error_code) # Error code if evaluation failed ``` -------------------------------- ### Get Feature Flag Variant Value with Fallback Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Retrieve a specific variant value for a feature flag, providing a fallback value if the flag is not enabled or the variant is not found. This method also makes an API call. ```python context = {"distinct_id": "user123"} # Get variant value with fallback button_color = mp.remote_flags.get_variant_value( "button-color", fallback_value="blue", context=context ) # Use the variant show_button(color=button_color) ``` -------------------------------- ### Mixpanel Constructor Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/Mixpanel.md Initializes the Mixpanel client. You can configure it with your project token, custom consumers, serializers, and feature flag configurations. ```APIDOC ## Mixpanel Constructor ### Description Initializes the Mixpanel client with a project token and optional configurations for consumers, serializers, and feature flags. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **token** (str) - Required - Your Mixpanel project token - **consumer** (Consumer or BufferedConsumer) - Optional - Custom consumer for controlling message delivery behavior. Defaults to Consumer(). - **serializer** (json.JSONEncoder) - Optional - JSONEncoder subclass for custom serialization (e.g., datetime handling). Defaults to DatetimeSerializer. - **local_flags_config** (LocalFlagsConfig) - Optional - Configuration for client-side feature flag evaluation with polling. Defaults to None. - **remote_flags_config** (RemoteFlagsConfig) - Optional - Configuration for server-side feature flag evaluation. Defaults to None. - **credentials** (ServiceAccountCredentials) - Optional - Service account credentials for server-to-server authentication (used for /import and /decide endpoints). Defaults to None. ### Request Example ```python from mixpanel import Mixpanel, ServiceAccountCredentials # Basic initialization with token mp = Mixpanel("YOUR_TOKEN") # With service account credentials credentials = ServiceAccountCredentials( username="service-account-username", secret="service-account-secret", project_id="123456" ) mp = Mixpanel("YOUR_TOKEN", credentials=credentials) # With local feature flags from mixpanel.flags.types import LocalFlagsConfig mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) # With custom consumer from mixpanel import BufferedConsumer consumer = BufferedConsumer(max_size=50) mp = Mixpanel("YOUR_TOKEN", consumer=consumer) ``` ### Response Returns: Mixpanel instance ``` -------------------------------- ### Get All Asynchronous Variants Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Asynchronously retrieves all feature flag variants for a given user context. This is useful for fetching all flag states at once. Returns a dictionary mapping flag keys to their respective `SelectedVariant` objects, or None if an error occurs. ```python import asyncio async def main(): mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} all_variants = await mp.remote_flags.aget_all_variants(context) if all_variants: for flag_key, variant in all_variants.items(): print(f"{flag_key}: {variant.variant_value}") asyncio.run(main()) ``` -------------------------------- ### Constructor Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Initializes the LocalFeatureFlagsProvider. While it can be instantiated directly, it's typically accessed via the Mixpanel constructor. ```APIDOC ## Constructor ### Description Initializes the LocalFeatureFlagsProvider with necessary configuration and callbacks. ### Parameters #### Parameters - **token** (str) - Required - Mixpanel project token - **config** (LocalFlagsConfig) - Required - Configuration object with API host, timeout, and polling settings - **version** (str) - Required - SDK version - **tracker** (Callable) - Required - Callback function for tracking exposure events - **credentials** (ServiceAccountCredentials) - Optional - Service account credentials for authentication ### Returns LocalFeatureFlagsProvider instance ### Example ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig config = LocalFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10, enable_polling=True, polling_interval_in_seconds=60 ) mp = Mixpanel("YOUR_TOKEN", local_flags_config=config) # Access via mp.local_flags ``` ``` -------------------------------- ### Get Variant Value for a Feature Flag Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Retrieve the specific variant value for a feature flag using `get_variant_value`. Provide a fallback value for cases where the flag is not found or evaluation fails. This method also automatically tracks exposure. ```python mp = Mixpanel("YOUR_TOKEN", local_flags_config=LocalFlagsConfig()) mp.local_flags.start_polling_for_definitions() context = {"distinct_id": "user123"} button_color = mp.local_flags.get_variant_value( "button-color", fallback_value="blue", context=context ) # button_color could be "blue", "red", "green", etc. ``` -------------------------------- ### Get Asynchronous Variant Value Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Asynchronously retrieves the variant value for a given feature flag key. Use this when you only need the specific value of a flag and not its associated metadata. Requires a fallback value in case the flag is not found or evaluation fails. ```python import asyncio async def main(): mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} button_color = await mp.remote_flags.aget_variant_value( "button-color", fallback_value="blue", context=context ) print(button_color) asyncio.run(main()) ``` -------------------------------- ### Instantiate LocalFeatureFlagsProvider Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/LocalFeatureFlagsProvider.md Instantiate the LocalFeatureFlagsProvider, typically via the Mixpanel constructor with a LocalFlagsConfig. This configures API host, timeout, and polling settings. ```python from mixpanel import Mixpanel from mixpanel.flags.types import LocalFlagsConfig config = LocalFlagsConfig( api_host="api.mixpanel.com", request_timeout_in_seconds=10, enable_polling=True, polling_interval_in_seconds=60 ) mp = Mixpanel("YOUR_TOKEN", local_flags_config=config) # Access via mp.local_flags ``` -------------------------------- ### Get Complete Feature Flag Variant Object Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Use `get_variant` to retrieve the full variant object, including its key, value, and experiment metadata. A fallback variant can be provided. The `reportExposure` parameter controls automatic exposure event tracking. ```python from mixpanel.flags.types import SelectedVariant mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} fallback = SelectedVariant(variant_key=None, variant_value="control") variant = mp.remote_flags.get_variant( "experiment-flag", fallback, context, reportExposure=True ) print(variant.variant_key) # e.g., "variant_a" print(variant.variant_value) # e.g., {"text": "New UI"} ``` -------------------------------- ### Get Asynchronous Variant Object Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/RemoteFeatureFlagsProvider.md Asynchronously retrieves the complete variant object for a feature flag. This object includes the variant key, value, and experiment metadata. It allows for tracking exposure events. Use this when you need more detailed information about the flag's variant and potentially track user exposure. ```python import asyncio from mixpanel.flags.types import SelectedVariant async def main(): mp = Mixpanel("YOUR_TOKEN", remote_flags_config=RemoteFlagsConfig()) context = {"distinct_id": "user123"} fallback = SelectedVariant(variant_key=None, variant_value="control") variant = await mp.remote_flags.aget_variant( "experiment-flag", fallback, context, reportExposure=True ) print(variant.variant_value) ``` -------------------------------- ### Track Basic and Nested Events Source: https://github.com/mixpanel/mixpanel-python/blob/master/_autodocs/api-reference/MixpanelIntegration.md Initialize the Mixpanel client and track events with simple or nested properties. Ensure you replace 'YOUR_TOKEN' with your actual Mixpanel project token. ```python from mixpanel import Mixpanel # Initialize mp = Mixpanel("YOUR_TOKEN") # Track an event mp.track("user123", "button_clicked", { "button_id": "submit", "page": "checkout" }) # Track with nested properties mp.track("user456", "purchase", { "amount": 99.99, "currency": "USD", "items": ["item1", "item2"], "metadata": {"campaign": "summer_sale"} }) ``` -------------------------------- ### Build Distribution Packages Source: https://github.com/mixpanel/mixpanel-python/blob/master/CLAUDE.md Creates distribution packages (sdist and wheel) for the Mixpanel Python library. These packages are used for publishing to PyPI. ```bash python -m build ```