Segment Analytics Python
analytics-python is Segment's official Python client library, designed for integrating analytics into any Python application. It simplifies data collection and routing to various analytics services via a single API. The library uses an internal queue for non-blocking calls, batching messages, and asynchronously flushing data to Segment's servers. Currently, this specific package (version 1.4.post1) is in maintenance mode, receiving only critical updates, with Segment recommending `segment-analytics-python` (version 2.x) for new feature support and active development.
Warnings
- breaking The `analytics-python` library (version 1.x) is officially in maintenance mode. This means it will send data as intended but will not receive new feature support, only critical maintenance updates. Segment recommends migrating to `segment-analytics-python` (version 2.x) for active development and new features.
- gotcha When performing historical data imports using the `timestamp` argument, some destinations like Google Analytics do not accept historical timestamped data, which can lead to data discrepancies or failures for specific integrations.
- gotcha In server-side applications, it is crucial to call `analytics.flush()` before the application exits or shuts down. This ensures that all buffered events are sent to Segment, preventing data loss, especially if not running in synchronous mode.
- gotcha If your application needs to send data to multiple Segment sources (each with a different `write_key`), you must initialize a new `Client` instance for each `write_key` to manage them independently.
Install
-
pip install analytics-python
Imports
- analytics
import segment.analytics as analytics
Quickstart
import os
import segment.analytics as analytics
# Configure with your Write Key from Segment
# It's recommended to load this from an environment variable or secure config
analytics.write_key = os.environ.get('SEGMENT_WRITE_KEY', 'YOUR_SEGMENT_WRITE_KEY')
# For testing, you might want to run in synchronous mode and debug
# analytics.debug = True
# analytics.sync_mode = True
# Identify a user
analytics.identify('user-123', {
'name': 'John Doe',
'email': 'john.doe@example.com',
'plan': 'premium'
})
# Track an event
analytics.track('user-123', 'Signed Up', {
'method': 'Email',
'plan': 'premium'
})
# Track a page view
analytics.page('user-123', 'Home Page', {
'title': 'Welcome to our site'
})
# Group a user with a company/account
analytics.group('user-123', 'group-456', {
'name': 'Acme Corp',
'industry': 'Technology'
})
# Alias users
analytics.alias('anonymous-id', 'user-123')
# Flush any buffered events before exiting (important in short-lived scripts)
analytics.flush()