Segment Analytics Python

2.3.5 · maintenance · verified Sun Apr 05

The `segment-analytics-python` library provides a hassle-free way to integrate analytics into any Python application. It acts as an official Python client for the Segment REST API, allowing users to send customer behavioral data to Segment, which then routes it to various analytics services and data warehouses. As of version 2.3.5, the library is in maintenance mode, meaning it will continue to send data as intended but will receive no new feature support and only critical maintenance updates from Segment.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Segment client, identify a user, track an event, record a page view, and associate a user with a group. It includes best practices for handling the `write_key` via environment variables and setting up error handling for development. Remember to replace `YOUR_SEGMENT_WRITE_KEY` or set the `SEGMENT_WRITE_KEY` environment variable.

import os
import segment.analytics as analytics

# It's recommended to set the write_key via an environment variable for security
WRITE_KEY = os.environ.get('SEGMENT_WRITE_KEY', 'YOUR_SEGMENT_WRITE_KEY')

if not WRITE_KEY or WRITE_KEY == 'YOUR_SEGMENT_WRITE_KEY':
    print("WARNING: SEGMENT_WRITE_KEY environment variable not set or using placeholder. Analytics calls will not be sent.")
    analytics.send = False # Disable sending if key is not set
else:
    analytics.write_key = WRITE_KEY
    print(f"Segment write_key set: {analytics.write_key[:4]}...{analytics.write_key[-4:]}")

# Configure for development (optional, but recommended to see errors)
analytics.debug = True
def on_error(error, items):
    print(f"An error occurred with Segment: {error}. Items: {items}")
analytics.on_error = on_error

# Identify a user
analytics.identify('user-123', {
    'name': 'John Doe',
    'email': 'john.doe@example.com',
    'plan': 'premium'
})

# Track an event
analytics.track('Sign Up Completed', {
    'method': 'email',
    'plan': 'premium'
})

# Page view (for server-side apps, typically not directly used for web page views)
analytics.page('App Home', {
    'path': '/home',
    'title': 'Homepage'
})

# Group (associate a user with a group, e.g., a company)
analytics.group('user-123', 'company-456', {
    'name': 'Acme Corp',
    'industry': 'Software'
})

# Flush any remaining events in the queue
analytics.flush()
print("Segment events sent (or queued if SEND_DISABLED is not set).")

view raw JSON →