Instrument and configure the Python SDK
After you complete Get started, use this guide to track events and properties, write plugins, control how events reach Amplitude, and flush events from processes that stop quickly. For exact signatures and every option, go to the Reference. For changes between versions, go to the Amplitude-Python changelog.
The samples on this page use one client:
from amplitude import Amplitude, BaseEvent, EventOptions, Identify, Revenue
client = Amplitude("AMPLITUDE_API_KEY")
Track events
The Python SDK sends five kinds of data: custom events, user properties, group membership, group properties, and revenue. Each has its own method. None of these methods returns a result. The outcome arrives later in a callback.
Track a custom event
Build a BaseEvent with an event type and a user_id or device_id, then pass it to track():
client.track(
BaseEvent(
event_type="Report Exported",
user_id="user-12345",
event_properties={"format": "csv", "rows": 1200},
)
)
BaseEvent also accepts every field of the HTTP V2 API event, such as app_version, platform, country, ip, time, and insert_id. For the full list, go to EventOptions. Set an insert_id when a retry from your own code could send the same event twice. Amplitude ignores a second event with the same insert_id and device_id within seven days.
Property values must be strings, numbers, booleans, Enum members, lists of those, or nested dictionaries. If one value has another type, such as a datetime, the SDK discards the whole dictionary without logging. To find discarded properties, go to Check what the SDK captured.
Change an event after you create it
Events support item access. Assigning a value with the wrong type logs an error and leaves the field unchanged:
event = BaseEvent("Report Exported", "user-12345")
event["groups"] = {"org_id": "15"}
event["app_version"] = "2.4.0"
client.track(event)
Set user properties
User properties describe the user, such as a plan or a role. Build an Identify object with one operation per property, and send it with identify(). Each method returns the same object, so calls chain:
identify = (
Identify()
.set("plan", "pro")
.set_once("first_seen_source", "newsletter")
.add("reports_exported", 1)
.append("visited_locations", "SFO")
.post_insert("unique_locations", "LAX")
.unset("trial_ends_at")
)
client.identify(identify, EventOptions(user_id="user-12345"))
identify() sends an $identify event that changes the user's properties without counting as a user action. Each property takes one operation per Identify object. A second operation on the same property logs Key or clear all operation already set., and the SDK ignores it. For every operation, including clear_all and the list operations prepend, pre_insert, and remove, go to Identify.
User properties apply to later events
The user's profile in User Lookup updates as soon as Amplitude receives the $identify event. Charts show the new values only on events sent after it. For details, go to User properties and events.
Assign a user to a group
Groups let you analyze users by account, organization, or another entity, for example counting the organizations that performed an event. Groups require the Accounts add-on.
set_group() puts a user in one or more groups of a group type. set_group() also sets the group type as a user property and replaces the user's earlier groups of that type.
client.set_group(
group_type="org_id",
group_name=["15", "21"],
event_options=EventOptions(user_id="user-12345"),
)
Pass one name as a string, or several as a list of strings. To attach groups to a single event without changing the user's groups, set groups on the event:
client.track(
BaseEvent("Report Exported", user_id="user-12345", groups={"org_id": ["15", "21"]})
)
Set group properties
To set properties on the group itself, pass an Identify object to group_identify(). A group identify event needs no user ID or device ID.
client.group_identify(
group_type="org_id",
group_name="15",
identify_obj=Identify().set("tier", "enterprise"),
)
Track revenue
Build a Revenue object for each purchase and send it with revenue(). The SDK sends the purchase as a revenue_amount event, and Amplitude's revenue charts read that event's properties.
purchase = Revenue(
price=3.99,
quantity=3,
product_id="com.example.premium",
revenue_type="purchase",
currency="USD",
)
client.revenue(purchase, EventOptions(user_id="user-12345"))
price must be a float: Revenue(price=4) logs Invalid price for revenue event and sends nothing. Write 4.0, or convert with float(). Amplitude computes revenue as price * quantity. For receipt verification fields and the other properties, go to Revenue. currency requires 1.1.5 or later.
Attach tracking plan details to every event
Set plan to record which tracking plan branch and version produced each event, and ingestion_metadata to name the system that sent it. The SDK adds both to every event that doesn't set its own.
from amplitude import Amplitude, BaseEvent, Config, IngestionMetadata, Plan
client = Amplitude(
"AMPLITUDE_API_KEY",
Config(
plan=Plan(branch="main", source="backend", version="3"),
ingestion_metadata=IngestionMetadata(source_name="billing-service", source_version="1.8.0"),
),
)
client.track(BaseEvent("Report Exported", user_id="user-12345"))
ingestion_metadata requires 1.1.0 or later.
Identity
How the SDK handles identity
The Python SDK keeps no identity state. It doesn't create or store a device ID, user ID, or session, so each event carries the identifiers you give it. Every event needs a user_id or a device_id. Amplitude rejects an ID shorter than five characters, or shorter than min_id_length when you set it.
Attribute an event to a user and a client session
To join server events with events from a browser or mobile SDK, send the same user_id, device_id, and session_id that the client SDK uses. session_id is the session's start time in milliseconds since the epoch.
client.track(
BaseEvent(
"Order Shipped",
user_id="user-12345",
device_id="5d3a1c9e-browser-device",
session_id=1762780800000,
)
)
Read the device ID and session ID in the client SDK, for example with getDeviceId() and getSessionId() in Browser SDK 2, and pass them to your server with the request.
Stop sending events
Set opt_out on the client's configuration to stop processing events, for example when a user withdraws consent. The SDK logs Skipped event for opt out config for each event it skips.
client.configuration.opt_out = True
client.track(BaseEvent("Report Exported", user_id="user-12345")) # skipped
client.configuration.opt_out = False
opt_out applies to the whole client, not to one user. To skip events for particular users, check consent before you call track(), or drop events in a plugin.
Plugins
How plugins run
Plugins change, filter, or forward events. client.add() registers a plugin, and client.remove() removes it. Each event passes through the plugin types in this order, in the thread that called track():
| Type | Runs | Return value |
|---|---|---|
PluginType.BEFORE | First. The built-in context plugin sets time, insert_id, and library here. | The event, or None to drop it. |
PluginType.ENRICHMENT | Next, in the order you added them. | The event, or None to drop it. |
PluginType.DESTINATION | Last. Each destination receives its own copy of the event. | Ignored. |
setup(client) runs once when you add the plugin. execute(event) runs for every event, including identify, group identify, and revenue events. An exception inside a plugin doesn't reach your code. The SDK logs the exception with a traceback and continues with the event as it was before that plugin.
PluginType also has an OBSERVE member, but version 1.3.0 can't register an observe plugin: client.add() raises KeyError: <PluginType.OBSERVE: 3>. Use an enrichment plugin that returns the event unchanged instead.
Enrich events
This enrichment plugin adds an incrementing event_id to each event. A lock keeps the counter correct when several threads call track().
from threading import Lock
from amplitude import EventPlugin, PluginType
class AddEventIdPlugin(EventPlugin):
def __init__(self, start=0):
super().__init__(PluginType.ENRICHMENT)
self.current_id = start
self.lock = Lock()
def execute(self, event):
with self.lock:
event.event_id = self.current_id
self.current_id += 1
return event
client.add(AddEventIdPlugin())
client.track(BaseEvent("Report Exported", user_id="user-12345"))
EventPlugin also routes each kind of event to its own method when you don't override execute(): track(event), identify(event), group_identify(event), and revenue(event). Override only the ones you need.
Filter events
Return None from an enrichment plugin to drop an event. This plugin drops events from internal test accounts:
from amplitude import EventPlugin, PluginType
class DropTestUsers(EventPlugin):
def __init__(self):
super().__init__(PluginType.ENRICHMENT)
def execute(self, event):
if event.user_id and event.user_id.startswith("test-"):
return None
return event
client.add(DropTestUsers())
client.track(BaseEvent("Report Exported", user_id="test-user-1")) # dropped
client.track(BaseEvent("Report Exported", user_id="user-12345")) # sent
Send events to another destination
Subclass DestinationPlugin to forward events somewhere other than Amplitude. Call super().__init__() and super().setup(client): they create and connect the destination's own plugin timeline, which self.timeline.process() needs.
import logging
from amplitude import DestinationPlugin
class LogDestination(DestinationPlugin):
def __init__(self):
super().__init__()
self.log = logging.getLogger("analytics-audit")
def setup(self, client):
super().setup(client)
def execute(self, event):
event = self.timeline.process(event)
self.log.warning("event: %s", event)
client.add(LogDestination())
client.track(BaseEvent("Report Exported", user_id="user-12345"))
self.timeline.process() runs the plugins you added to this destination with destination.add(plugin), so you can transform events for one destination only. The built-in Amplitude destination keeps sending every event.
Data delivery
How the SDK uploads events
track() returns after the plugins run. The event then waits in an in-memory queue, and a background thread uploads it:
- When: every
flush_interval_millis(10 seconds by default), or as soon asflush_queue_size(200 by default) events are ready, or when you callflush()orshutdown(). - How much: up to
flush_queue_sizeevents per request, in parallel requests from a pool of 16 threads. - Retries: timeouts,
5xxresponses, and network errors retry with backoff, from 100 milliseconds up to 3.2 seconds. The SDK drops an event afterflush_max_retries(12) failed attempts. - Large batches: after a
413response for a batch, the SDK lowers the batch size for later requests and retries. - Rate limits: after a
429response, the SDK drops events from users or devices over their daily quota and retries other throttled events after 30 seconds.
Queued events live only in memory. If something kills the process, you lose the events still in the queue.
Tune batching
Raise flush_queue_size to send fewer, larger requests, or lower flush_interval_millis to send sooner:
from amplitude import Amplitude, BaseEvent, Config
client = Amplitude(
"AMPLITUDE_API_KEY",
Config(flush_queue_size=100, flush_interval_millis=2000),
)
client.track(BaseEvent("Report Exported", user_id="user-12345"))
You can also change most options after you create the client, through client.configuration. For example, client.configuration.flush_queue_size = 100.
Choose a data region
Set server_zone="EU" for projects in Amplitude's EU data center. The default is "US".
from amplitude import Amplitude, BaseEvent, Config
client = Amplitude("AMPLITUDE_API_KEY", Config(server_zone="EU"))
client.track(BaseEvent("Report Exported", user_id="user-12345"))
Send large volumes with the batch API
Set use_batch=True to send to the Batch Event Upload API, which accepts higher volumes per user and device than the HTTP V2 API. Batching options apply the same way in both modes.
from amplitude import Amplitude, BaseEvent, Config
client = Amplitude("AMPLITUDE_API_KEY", Config(use_batch=True))
client.track(BaseEvent("Report Exported", user_id="user-12345"))
Send events through a proxy
Set server_url to send every request to your own endpoint. server_url overrides server_zone and use_batch, so set the full URL, including the API path your proxy forwards to.
from amplitude import Amplitude, Config
client = Amplitude(
"AMPLITUDE_API_KEY",
Config(server_url="https://amplitude-proxy.example.com/2/httpapi"),
)
The proxy must return Amplitude's JSON response body with its code field. The SDK reads code to decide whether to retry.
Get the result of each upload
Set a client-level callback in Config, or a callback on one event. The SDK calls it once per event, with (event, code, message), when the event succeeds or finally fails. Callbacks run on the SDK's upload threads, so keep them short and thread-safe.
from amplitude import Amplitude, BaseEvent, Config
def on_result(event, code, message):
if code != 200:
print(f"{event.event_type} failed: {code} {message}")
client = Amplitude("AMPLITUDE_API_KEY", Config(callback=on_result))
client.track(BaseEvent("Report Exported", user_id="user-12345"))
For every code and message, go to Read the upload result.
Control SDK logging
The SDK logs to logging.getLogger("amplitude"). To use your own logger, pass it as logger. Set event_log_level to choose the level of the upload log, which writes one line per event: EventLogLevel.INFO (default), EventLogLevel.DEBUG, or EventLogLevel.NONE. High-volume services often set NONE and rely on the callback.
import logging
from amplitude import Amplitude, BaseEvent, Config, EventLogLevel
client = Amplitude(
"AMPLITUDE_API_KEY",
Config(logger=logging.getLogger("myapp.analytics"), event_log_level=EventLogLevel.DEBUG),
)
client.track(BaseEvent("Report Exported", user_id="user-12345"))
event_log_level requires 1.3.0 or later. Errors, such as Invalid API Key, always log at ERROR.
Serverless and short-lived processes
Flush before the process exits
The SDK registers shutdown() to run when the interpreter exits normally, so a script that reaches its end sends its queued events. This exit handler requires version 1.1.1 or later. Exit handlers don't run after os._exit() or SIGKILL, or when a platform freezes the process between requests. In those cases, flush the client yourself.
flush() returns a list with one item per destination plugin: a concurrent.futures.Future, or None when the queue was empty. Wait on each future to block until the upload finishes:
client.track(BaseEvent("Report Exported", user_id="user-12345"))
for future in client.flush():
if future:
future.result()
shutdown() flushes, waits, and stops the client's threads. After shutdown(), the client skips every event, so call it only when the process is done with the client.
Flush in a serverless function
In AWS Lambda, Google Cloud Functions, and Azure Functions, create the client outside the handler so warm invocations reuse it, and flush before the handler returns. The platform can freeze the process right after the response, before the SDK's timer fires.
from amplitude import Amplitude, BaseEvent
client = Amplitude("AMPLITUDE_API_KEY")
def handler(event, context):
client.track(BaseEvent("Report Exported", user_id=event["user_id"]))
for future in client.flush():
if future:
future.result()
return {"statusCode": 200}
Use the SDK in forking servers
Servers such as Gunicorn and Celery fork worker processes. Background threads don't survive a fork, so create the client in each worker, after the fork. For example, create it in a Gunicorn post_fork hook or a Celery worker_process_init signal handler, or create it lazily on first use.
Send events to more than one project
Create one client per project. Clients don't share queues, threads, or configuration.
from amplitude import Amplitude, BaseEvent
production = Amplitude("PROJECT_A_API_KEY")
analytics_sandbox = Amplitude("PROJECT_B_API_KEY")
event = BaseEvent("Report Exported", user_id="user-12345")
production.track(event)
analytics_sandbox.track(event)
Was this helpful?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.