Ampli for Python SDK
Amplitude Data supports tracking analytics events from Python apps (Python 3.6 or higher). Ampli packages the generated tracking library as a Python package.
- shell
pip install amplitude-analytics - shell
npm install -g @amplitude/ampli Pull the Ampli Wrapper into your project
shellampli pull [--path ./ampli]- python
from .ampli import * ampli.load(LoadOptions( client=LoadClientOptions(AMPLITUDE_API_KEY) )) Identify users and set user properties
pythonampli.identify("user_id", Identify(userProp="A trait associated with this user"))Track events with strongly typed methods and classes
pythonampli.song_played('user_id', SongPlayed(song_id="song-1")) ampli.track('user-id', new SongFavorited(song_id="song-2"));Flush events before application exit
pythonampli.flush();Verify implementation status with CLI
shellampli status [--update]
Install the Amplitude SDK
If you haven't already, install the core Amplitude SDK dependencies.
pip install amplitude-analytics
Install Ampli
You can install the Ampli CLI from Homebrew or NPM.
npm install -g @amplitude/ampli
Pull the Ampli wrapper into your project
Run the Ampli CLI pull command from the project root directory to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan.
ampli pull
Ampli prompts you to log in to your workspace and select a source.
➜ ampli pull
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
? Organization: Amplitude
? Workspace: My Workspace
? Source: My Source
Initialize Ampli
Initialize Ampli in your code. The load() method requires a LoadOptions instance that specifies configuration options for the Ampli Wrapper.
from .ampli import *
ampli.load(LoadOptions(
client=LoadClientOptions(AMPLITUDE_API_KEY)
))
LoadOptions accepts the following arguments:
| Argument | Required | Default | Description |
|---|---|---|---|
disabled | No | False | When True, all Ampli Wrapper calls are no-ops. Useful in local or development environments. |
client | No | None | A LoadClientOptions instance that specifies configuration options for the Amplitude core SDK client. |
LoadClientOptions accepts the following arguments:
| Argument | Required | Default | Description |
|---|---|---|---|
instance | Required if api_key isn't set | None | The Amplitude instance to use. By default, Ampli creates an instance. |
api_key | Required if instance isn't set | None | The API key to use. Overrides the API key configured in your tracking plan. |
configuration | No | None | The Amplitude configuration to use. Overrides the default configuration. |
Identify
Call identify() to identify a user in your app, associate all future events with their identity, or set their user properties. Ampli generates types for user properties from your tracking plan.
The identify() function accepts a string user_id, an Identify event instance, and an optional EventOptions.
For example, if your tracking plan contains a user property called role with the type string:
ampli.identify("user_id", Identify(role="admin"))
The options argument accepts Amplitude fields for this call, such as device_id.
ampli.identify("user_id", Identify(role="admin"), EventOptions(device_id="device_id"))
Group identify
Call group_identify() to identify a group in your app and set or update group properties. Ampli generates types for group properties from your tracking plan.
The group_identify() function accepts a string group_type, a string group_name, a Group event instance, and an optional EventOptions.
For example, if your tracking plan contains a group sport:football with a property called total_member of type integer:
ampli.group_identify("sport", "football", Group(total_member=23))
Set group
Call set_group() to associate a user with their group, for example, their department or company. The set_group() function accepts user_id, group_type, group_name, and an optional EventOptions.
ampli.set_group("user_id", "sport", "football")
group_name accepts a single group name string or a list of multiple group names.
ampli.set_group("user_id", "sport", ["football", "basketball"])
Track
To track an event, call the event's corresponding function. Every event in your tracking plan gets its own function in the Ampli Wrapper. Structure the call like this:
ampli.event_name("user_id", EventName(...), EventOptions(...))
The optional EventOptions argument accepts Amplitude fields, such as device_id.
For example, if your tracking plan contains an event called songPlayed with two required properties: songId (string) and songFavorited (boolean):
ampli.song_played('user_id', SongPlayed(
song_id = 'songId', # str,
song_favorited = True, # bool
))
Ampli also generates a class for each event. Send event objects using the generic track method.
my_event = SongPlayed(
song_id = 'songId', # str,
song_favorited = True, # bool
)
ampli.track('user_id', SongPlayed(
song_id = 'songId', # str,
song_favorited = True, # bool
), EventOptions(device_id="device_id"))
Flush
The Ampli wrapper queues events and sends them automatically based on the flushQueueSize and flushInterval configuration values.
Call flush() to send any pending events immediately. The flush() method returns a promise that you can use to ensure all pending events send before continuing. Call flush() before the application exits.
ampli.flush();
Plugin
Plugins extend Amplitude's behavior. For example, an enrichment plugin modifies event properties, and a destination plugin sends data to third-party APIs.
First, define your plugin. The following example shows a destination plugin:
from amplitude import DestinationPlugin, PluginType, BaseEvent, IdentifyEvent
from analytics import Client as SegmentClient
class SegmentPlugin(DestinationPlugin):
def __init__(self, write_key):
self.plugin_type = PluginType.DESTINATION
self.configuration = None
self.segment = SegmentClient(write_key)
def setup(self, client):
self.configuration = client.configuration
def execute(self, event: BaseEvent) -> None:
if isinstance(event, IdentifyEvent):
self.segment.identify(event.user_id, event.user_properties)
elif isinstance(event, BaseEvent):
self.segment.track(event.user_id, event.event_type, event.event_properties)
Add your plugin after you initialize Ampli:
ampli.client.add(SegmentPlugin("write_key"))
Status
Verify that your code implements events with the status command:
ampli status [--update]
The output displays status and indicates what events are missing.
➜ ampli status
✘ Verifying event tracking implementation in source code
✔ Song Played (1 location)
✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total
Troubleshooting
ImportError: Attempted relative import with no known parent package
This error occurs when you run a script directly with python3 main.py and use a relative import like from .ampli import *. Python doesn't recognize the module structure when you run scripts directly.
There are two solutions.
Option 1: Use absolute imports
Use an absolute import based on your package structure:
from ampli import *
Or if your Ampli wrapper is in a package:
from your_package.ampli import *
Option 2: Run as a module
Run your script as a module:
python3 -m your_package.main
Was this helpful?