Python SDK reference

This reference documents every public export of amplitude-analytics and every Config option, verified against version 1.3.0. For tasks, go to Instrument and configure. For changes between versions, go to the Amplitude-Python changelog.

python
from amplitude import (
    Amplitude, Config, BaseEvent, EventOptions, Identify, Revenue,
    IdentifyEvent, GroupIdentifyEvent, RevenueEvent, Plan, IngestionMetadata,
    EventPlugin, DestinationPlugin, PluginType, EventLogLevel,
)

The package has no module-level tracking functions. Every method on this page belongs to an Amplitude client instance, and each instance has its own configuration, queue, and threads.

Results and callbacks

Tracking methods return None. The SDK reports each event's outcome later, on an upload thread, by calling the client's callback and the event's own callback with three arguments:

For every code and message, go to Read the upload result.

Setup

Amplitude

Creates a client, starts its plugin timeline, and adds the built-in Amplitude destination and context plugins. The constructor also registers shutdown() to run when the interpreter exits.

python
Amplitude(api_key: str, configuration: Optional[Config] = None)

The client exposes its configuration as client.configuration. You can change most options on it after you create the client.

python
from amplitude import Amplitude, BaseEvent, Config, EventOptions, Identify, Revenue

client = Amplitude("AMPLITUDE_API_KEY", Config(flush_interval_millis=5000))

add

Adds a plugin and calls its setup(client). Returns the client, so calls chain.

python
add(plugin: Plugin) -> Amplitude

remove

Removes a plugin from every plugin type. Returns the client.

python
remove(plugin: Plugin) -> Amplitude

flush

Uploads every queued event now. Returns a list with one item per destination plugin. Each item is a concurrent.futures.Future that completes after the upload and its callbacks finish, or None when that destination had nothing queued.

python
flush() -> List[Optional[Future]]
python
client.track(BaseEvent("Report Exported", user_id="user-12345"))
for future in client.flush():
    if future:
        future.result()

shutdown

Flushes queued events, waits for the uploads, and stops the client's threads. shutdown() also sets configuration.opt_out to True, so the client skips every later event. The SDK calls shutdown() automatically when the interpreter exits. Automatic shutdown requires 1.1.1 or later.

python
shutdown() -> None

Tracking

track

Runs the event through the plugins in the calling thread, then queues it for upload.

python
track(event: BaseEvent) -> None
python
client.track(BaseEvent("Report Exported", user_id="user-12345", event_properties={"format": "csv"}))

identify

Sends an $identify event that applies the operations in an Identify object to the user's properties. Logs Empty identify properties and sends nothing when the object has no operations.

python
identify(identify_obj: Identify, event_options: EventOptions, event_properties: Optional[dict] = None) -> None
python
client.identify(Identify().set("plan", "pro"), EventOptions(user_id="user-12345"))

set_group

Sends an $identify event that sets the user's groups for one group type, and sets the same value as a user property.

python
set_group(group_type: str, group_name: Union[str, List[str]], event_options: EventOptions) -> None
python
client.set_group("org_id", ["15", "21"], EventOptions(user_id="user-12345"))

group_identify

Sends a $groupidentify event that applies the operations in an Identify object to one group's properties. Needs no user or device ID. Logs Empty group identify properties and sends nothing when the object has no operations.

python
group_identify(group_type: str, group_name: str, identify_obj: Identify,
               event_options: Optional[EventOptions] = None,
               event_properties: Optional[dict] = None,
               user_properties: Optional[dict] = None) -> None
python
client.group_identify("org_id", "15", Identify().set("tier", "enterprise"))

revenue

Sends a revenue_amount event built from a Revenue object. Logs Invalid price for revenue event and sends nothing when the price isn't a float or the quantity isn't a positive int.

python
revenue(revenue_obj: Revenue, event_options: EventOptions) -> None
python
client.revenue(Revenue(price=9.99, product_id="com.example.pro"), EventOptions(user_id="user-12345"))

Identify operations

Identify builds property operations for identify() and group_identify(). Each method returns the same object, so calls chain. Each object accepts one operation per property. A later operation on the same property, or any operation after clear_all(), logs Key or clear all operation already set., and the SDK ignores it.

python
Identify()

Values accept str, int, float, bool, lists of those or of dictionaries, and dictionaries of those types. Amplitude creates a missing list property as an empty list before a list operation.

Revenue fields

Revenue describes one purchase for revenue(). The SDK sends its fields as event properties with a $ prefix, such as $price and $productId.

python
Revenue(price: float, quantity: int = 1, product_id: Optional[str] = None,
        revenue_type: Optional[str] = None, receipt: Optional[str] = None,
        receipt_sig: Optional[str] = None, properties: Optional[dict] = None,
        revenue: Optional[float] = None, currency: Optional[str] = None)

Events

BaseEvent

A custom event. Subclass of EventOptions.

python
BaseEvent(event_type: str, user_id: Optional[str] = None, device_id: Optional[str] = None,
          event_properties: Optional[dict] = None, user_properties: Optional[dict] = None,
          groups: Optional[dict] = None, group_properties: Optional[dict] = None,
          callback: Optional[Callable[[BaseEvent, int, Optional[str]], None]] = None,
          ...)  # and every EventOptions field as a keyword argument

Events support item access: event["app_version"] reads a field, and event["app_version"] = "2.4.0" sets one. For a value of the wrong type, the SDK logs Event property <key> expected <type> but received <type>. and doesn't store the value. The SDK neither stores nor logs a property dictionary with an unsupported value type.

str(event) returns the JSON body the SDK uploads. event.retry is the number of failed upload attempts so far.

The SDK modifies the payload as it builds it:

  • It truncates string values longer than 1,024 characters.
  • It replaces a dictionary with more than 1,024 keys with {}.
  • It omits properties set to None.
  • It sends Enum members as their .value.

EventOptions

The optional event fields. Pass them to BaseEvent, or as an EventOptions object to identify(), set_group(), group_identify(), and revenue(). These fields map to the HTTP V2 API event fields.

The SDK sets library to amplitude-python/<version> on every event.

IdentifyEvent, GroupIdentifyEvent, and RevenueEvent

Subclasses of BaseEvent with a fixed event_type: $identify, $groupidentify, and revenue_amount. identify(), set_group(), group_identify(), and revenue() build them for you. Plugins can check an event's class to tell these event types apart. Their constructors take the same fields as BaseEvent, without event_type.

Plugins

Plugin

The abstract base class of all plugins.

EventPlugin

The base class for BEFORE and ENRICHMENT plugins. Its execute() routes each event to one of four methods by class. Each returns the event by default. Return a modified event, or None to drop it.

python
EventPlugin(plugin_type: PluginType)
python
from amplitude import EventPlugin, PluginType

class AddEnvironment(EventPlugin):
    def __init__(self):
        super().__init__(PluginType.ENRICHMENT)

    def track(self, event):
        event.event_properties = {**(event.event_properties or {}), "environment": "production"}
        return event

client.add(AddEnvironment())
client.track(BaseEvent("Report Exported", user_id="user-12345"))

DestinationPlugin

The base class for destinations. Its plugin_type is PluginType.DESTINATION, and it owns a timeline of plugins that apply to this destination only. Override execute(event), and call self.timeline.process(event) in it to run those plugins. The SDK ignores the return value.

python
DestinationPlugin()

For an example, go to Send events to another destination.

PluginType

An Enum of plugin types, in the order they run.

Types

Plan

Tracking plan details that the SDK adds to events as plan. Set it with Config.plan or per event.

python
Plan(branch: Optional[str] = None, source: Optional[str] = None,
     version: Optional[str] = None, version_id: Optional[str] = None)

IngestionMetadata

Details about the system that sent the event, added to events as ingestion_metadata. Requires 1.1.0 or later.

python
IngestionMetadata(source_name: Optional[str] = None, source_version: Optional[str] = None)

EventLogLevel

An Enum for Config.event_log_level. Requires 1.3.0 or later.

Storage and StorageProvider

Abstract classes in amplitude.storage for the buffer that holds events until upload. A StorageProvider implements get_storage(), which returns a Storage. A Storage implements push(event, delay=0), pull(batch_size), and pull_all(). It also needs the members the upload threads call on the built-in InMemoryStorage: setup(configuration, workers), lock (a threading.Condition), total_events, and wait_time. Subclass InMemoryStorage unless you need a different buffer. The built-in InMemoryStorageProvider is the default.

Configuration options

Config holds every client option. Pass it as the second argument of Amplitude(). All arguments are optional. After you create the client, read or change options as attributes of client.configuration.

python
Config(api_key: str = None, flush_queue_size: int = 200, flush_interval_millis: int = 10000,
       flush_max_retries: int = 12, logger=logging.getLogger("amplitude"),
       min_id_length: Optional[int] = None, callback: Optional[Callable] = None,
       server_zone: str = "US", use_batch: bool = False, server_url: Optional[str] = None,
       storage_provider: Optional[StorageProvider] = None, plan: Plan = None,
       ingestion_metadata: IngestionMetadata = None,
       event_log_level: EventLogLevel = EventLogLevel.INFO)
python
from amplitude import Amplitude, BaseEvent, Config, EventLogLevel

config = Config(
    flush_queue_size=100,
    flush_interval_millis=2000,
    min_id_length=5,
    event_log_level=EventLogLevel.DEBUG,
)
client = Amplitude("AMPLITUDE_API_KEY", config)
client.track(BaseEvent("Report Exported", user_id="user-12345"))

Project and endpoint

Delivery

Identity and validation

Logging

Tracking plan and metadata

Attributes without a constructor argument

Config.is_valid() returns False when api_key is empty, flush_queue_size or flush_interval_millis isn't positive, or min_id_length isn't a positive integer. The client doesn't call it, so check it yourself if you build a Config from user input.

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.

On this page