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.
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:
| Argument | Type | Description |
|---|---|---|
event | BaseEvent | The event as sent, after every plugin ran. |
code | int | The HTTP status code, or -1 when the request never got a response. |
message | str | A description of the outcome, such as Event sent successfully. |
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.
Amplitude(api_key: str, configuration: Optional[Config] = None)
| Parameter | Type | Description |
|---|---|---|
api_key | str | Your Amplitude project API key. Overwrites configuration.api_key. |
configuration | Config | Optional. Refer to Configuration options. Defaults to a new Config(). |
The client exposes its configuration as client.configuration. You can change most options on it after you create the client.
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.
add(plugin: Plugin) -> Amplitude
| Parameter | Type | Description |
|---|---|---|
plugin | Plugin | An instance of a plugin class. |
remove
Removes a plugin from every plugin type. Returns the client.
remove(plugin: Plugin) -> Amplitude
| Parameter | Type | Description |
|---|---|---|
plugin | Plugin | The same instance you passed to add(). |
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.
flush() -> List[Optional[Future]]
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.
shutdown() -> None
Tracking
track
Runs the event through the plugins in the calling thread, then queues it for upload.
track(event: BaseEvent) -> None
| Parameter | Type | Description |
|---|---|---|
event | BaseEvent | The event. It needs an event_type, and a user_id or device_id. |
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.
identify(identify_obj: Identify, event_options: EventOptions, event_properties: Optional[dict] = None) -> None
| Parameter | Type | Description |
|---|---|---|
identify_obj | Identify | The user property operations. |
event_options | EventOptions | Identifies the user. Needs a user_id or device_id. |
event_properties | dict | Optional. Event properties for the $identify event. |
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.
set_group(group_type: str, group_name: Union[str, List[str]], event_options: EventOptions) -> None
| Parameter | Type | Description |
|---|---|---|
group_type | str | The group type, for example "org_id". |
group_name | str or List[str] | One group name, or a list for several groups. |
event_options | EventOptions | Identifies the user. Needs a user_id or device_id. |
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.
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
| Parameter | Type | Description |
|---|---|---|
group_type | str | The group type. |
group_name | str | The group name. |
identify_obj | Identify | The group property operations. |
event_options | EventOptions | Optional. Extra fields for the event, such as user_id. |
event_properties | dict | Optional. Event properties for the $groupidentify event. |
user_properties | dict | Optional. User properties for the $groupidentify event. |
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.
revenue(revenue_obj: Revenue, event_options: EventOptions) -> None
| Parameter | Type | Description |
|---|---|---|
revenue_obj | Revenue | The purchase. Refer to Revenue. |
event_options | EventOptions | Identifies the user. Needs a user_id or device_id. |
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.
Identify()
| Method | Operation | Description |
|---|---|---|
set(key, value) | $set | Sets the value. |
set_once(key, value) | $setOnce | Sets the value only if the property has none. |
add(key, value) | $add | Adds a number to a numeric property. Amplitude treats a missing property as 0. Ignores a non-number value without logging. |
append(key, value) | $append | Appends one value, or each value of a list, to a list property. |
prepend(key, value) | $prepend | Prepends values to a list property. |
post_insert(key, value) | $postInsert | Appends values not already in the list. |
pre_insert(key, value) | $preInsert | Prepends values not already in the list. |
remove(key, value) | $remove | Removes values from a list property. |
unset(key) | $unset | Removes the property. |
clear_all() | $clearAll | Removes every property of the user. You can't undo it. |
is_valid() | Not applicable | Returns True if the object has at least one operation. |
user_properties (property) | Not applicable | A copy of the operations, for example {"$set": {"plan": "pro"}}. |
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.
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)
| Parameter | Type | Default | Description |
|---|---|---|---|
price | float | No default | Required. The unit price. Can be negative, for refunds. Must be a float; an int fails validation. |
quantity | int | 1 | The number of units. Must be a positive int. |
product_id | str | None | An identifier for the product. |
revenue_type | str | None | The revenue type, for example "purchase", "refund", or "tax". Required for revenue verification. |
receipt | str | None | The receipt identifier. Required for revenue verification. |
receipt_sig | str | None | The receipt signature. Required for revenue verification. |
properties | dict | None | Extra event properties for the revenue event. |
revenue | float | None | The total revenue. Amplitude uses price * quantity instead when both are set. |
currency | str | None | The currency code, for example "USD". Requires 1.1.5 or later. |
| Method | Description |
|---|---|
set_receipt(receipt, receipt_signature) | Sets receipt and receipt_sig. Returns the object. |
is_valid() | Returns True when price is a float and quantity is a positive int. |
to_revenue_event() | Returns a RevenueEvent with the revenue fields as event properties. |
Events
BaseEvent
A custom event. Subclass of EventOptions.
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
| Parameter | Type | Description |
|---|---|---|
event_type | str | The event name. Required. |
event_properties | dict | Properties of the event. |
user_properties | dict | User properties to set with the event. |
groups | dict | Event-level groups, as {group_type: group_name}. The name can be a list of strings. |
group_properties | dict | Group properties sent with the event. |
callback | callable | Called with (event, code, message) when this event succeeds or finally fails. Runs in addition to the client callback. |
Every EventOptions field | Refer to EventOptions | Keyword arguments. An unknown keyword raises TypeError. |
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
Enummembers 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.
| Field | Type | Description |
|---|---|---|
user_id | str | The user ID. An event needs a user_id or device_id. |
device_id | str | The device ID. |
time | int | The event time, in milliseconds since the epoch. Defaults to the time of track(). |
insert_id | str | A unique ID Amplitude uses to deduplicate events within seven days. Defaults to a random UUID. |
session_id | int | The session start time, in milliseconds since the epoch. |
event_id | int | A counter that orders events with the same user and time. |
app_version | str | The app version. |
version_name | str | The app version name. Requires 1.1.0 or later. |
platform | str | The platform. |
os_name | str | The operating system or browser name. |
os_version | str | The operating system or browser version. |
device_brand | str | The device brand. |
device_manufacturer | str | The device manufacturer. |
device_model | str | The device model. |
carrier | str | The mobile carrier. |
country | str | The country. |
region | str | The region or state. |
city | str | The city. |
dma | str | The Designated Market Area. |
language | str | The language. |
location_lat | float | The latitude. |
location_lng | float | The longitude. |
ip | str | The IP address Amplitude uses for location. |
user_agent | str | The user agent string. Requires 1.2.0 or later. |
idfa | str | The iOS advertising identifier. |
idfv | str | The iOS identifier for vendor. |
adid | str | The Google Play Services advertising ID. |
android_id | str | The Android ID. |
price | float | The item price, for revenue on a custom event. |
quantity | int | The item quantity. |
revenue | float | The revenue. Amplitude uses price * quantity instead when all three are set. |
product_id | str | The product identifier. |
revenue_type | str | The revenue type. |
currency | str | The currency code. Requires 1.1.5 or later. |
partner_id | str | A partner identifier. |
plan | Plan | Tracking plan details. Overrides Config.plan. |
ingestion_metadata | IngestionMetadata | Ingestion source details. Overrides Config.ingestion_metadata. Requires 1.1.0 or later. |
callback | callable | The event-level callback. |
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.
| Member | Description |
|---|---|
plugin_type | A PluginType. Set it in the constructor. |
setup(client) | client.add() calls it once. The default implementation does nothing. |
execute(event) | Abstract. Called for every event. |
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.
EventPlugin(plugin_type: PluginType)
| Method | Receives |
|---|---|
track(event) | BaseEvent instances that aren't one of the classes below. |
identify(event) | IdentifyEvent |
group_identify(event) | GroupIdentifyEvent |
revenue(event) | RevenueEvent |
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.
DestinationPlugin()
| Method | Description |
|---|---|
setup(client) | Connects timeline to the client. Call super().setup(client) when you override it. |
add(plugin) | Adds a plugin to this destination's timeline. Returns the destination. |
remove(plugin) | Removes a plugin from this destination's timeline. Returns the destination. |
execute(event) | Called with a copy of each event. Override it to send the event. |
shutdown() | client.shutdown() calls it. Override it to flush and close connections. |
For an example, go to Send events to another destination.
PluginType
An Enum of plugin types, in the order they run.
| Member | Value | Description |
|---|---|---|
BEFORE | 0 | Runs first. The built-in context plugin uses it. |
ENRICHMENT | 1 | Runs after BEFORE plugins. |
DESTINATION | 2 | Runs last, with a copy of the event. |
OBSERVE | 3 | Not supported in 1.3.0. client.add() raises KeyError for a plugin of this type. |
Types
Plan
Tracking plan details that the SDK adds to events as plan. Set it with Config.plan or per event.
Plan(branch: Optional[str] = None, source: Optional[str] = None,
version: Optional[str] = None, version_id: Optional[str] = None)
| Parameter | Type | Description |
|---|---|---|
branch | str | The tracking plan branch. |
source | str | The tracking plan source. |
version | str | The tracking plan version. |
version_id | str | The tracking plan version ID. Sent as versionId. |
IngestionMetadata
Details about the system that sent the event, added to events as ingestion_metadata. Requires 1.1.0 or later.
IngestionMetadata(source_name: Optional[str] = None, source_version: Optional[str] = None)
| Parameter | Type | Description |
|---|---|---|
source_name | str | The name of the sending system. |
source_version | str | The version of the sending system. |
EventLogLevel
An Enum for Config.event_log_level. Requires 1.3.0 or later.
| Member | Value | Description |
|---|---|---|
NONE | 0 | Doesn't log upload results per event. |
DEBUG | 1 | Logs upload results at DEBUG. |
INFO | 2 | Logs upload results at INFO. The default. |
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.
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)
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
| Option | Type | Default | Description |
|---|---|---|---|
api_key | str | None | The project API key. The Amplitude() constructor overwrites it with its api_key argument. |
server_zone | str | "US" | The data center: "US" or "EU". |
use_batch | bool | False | When True, sends to the Batch Event Upload API (/batch) instead of the HTTP V2 API (/2/httpapi). |
server_url | str | None (derived from server_zone and use_batch) | A custom upload URL, such as a proxy. When set, server_zone and use_batch don't apply. Reading server_url returns the URL in use. |
Delivery
| Option | Type | Default | Description |
|---|---|---|---|
flush_queue_size | int | 200 | The maximum number of events per request. The SDK uploads early when this many events are ready. A 413 response lowers the effective value. |
flush_interval_millis | int | 10000 | Milliseconds between scheduled uploads. |
flush_max_retries | int | 12 | The number of failed upload attempts after which the SDK drops an event. |
callback | callable | None | Called with (event, code, message) for every event that succeeds or finally fails. Refer to Results and callbacks. |
storage_provider | StorageProvider | InMemoryStorageProvider() | Creates the buffer that holds events until upload. Refer to Storage and StorageProvider. |
Identity and validation
| Option | Type | Default | Description |
|---|---|---|---|
min_id_length | int | None (Amplitude enforces 5) | The minimum accepted length of user_id and device_id. The SDK sends it as options.min_id_length with each request. Must be a positive integer. |
Logging
| Option | Type | Default | Description |
|---|---|---|---|
logger | logging.Logger | logging.getLogger("amplitude") | The logger for every SDK message. |
event_log_level | EventLogLevel | EventLogLevel.INFO | The level of the per-event upload log line. EventLogLevel.NONE turns it off. Requires 1.3.0 or later. |
Tracking plan and metadata
| Option | Type | Default | Description |
|---|---|---|---|
plan | Plan | None | Added to every event that has no plan. |
ingestion_metadata | IngestionMetadata | None | Added to every event that has no ingestion_metadata. Requires 1.1.0 or later. |
Attributes without a constructor argument
| Attribute | Type | Default | Description |
|---|---|---|---|
opt_out | bool | False | When True, the client skips every event. Set it on client.configuration. Config(opt_out=True) raises TypeError. shutdown() sets it to True. |
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.
これは役に立ちましたか?
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.