Segment Analytics Python

1.4.post1 · maintenance · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Segment client with a write key and send common analytics events like `identify`, `track`, `page`, `group`, and `alias`. It includes a crucial `flush()` call to ensure all events are sent, especially in applications that might terminate quickly.

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()

view raw JSON →