On this page

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.

  1. Install the Amplitude SDK

    shell
    pip install amplitude-analytics
    
  2. Install the Ampli CLI

    shell
    npm install -g @amplitude/ampli
    
  3. Pull the Ampli Wrapper into your project

    shell
    ampli pull [--path ./ampli]
    
  4. Initialize the Ampli Wrapper

    python
    from .ampli import *
    
    
    ampli.load(LoadOptions(
      client=LoadClientOptions(AMPLITUDE_API_KEY)
    ))
    
  5. Identify users and set user properties

    python
    ampli.identify("user_id", Identify(userProp="A trait associated with this user"))
    
  6. Track events with strongly typed methods and classes

    python
    ampli.song_played('user_id', SongPlayed(song_id="song-1"))
    ampli.track('user-id', new SongFavorited(song_id="song-2"));
    
  7. Flush events before application exit

    python
    ampli.flush();
    
  8. Verify implementation status with CLI

    shell
    ampli status [--update]
    

Install the Amplitude SDK

If you haven't already, install the core Amplitude SDK dependencies.

bash
pip install amplitude-analytics

Install Ampli

You can install the Ampli CLI from Homebrew or NPM.

bash
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.

bash
ampli pull

Ampli prompts you to log in to your workspace and select a source.

bash
 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.

python
from .ampli import *

ampli.load(LoadOptions(
   client=LoadClientOptions(AMPLITUDE_API_KEY)
))

LoadOptions accepts the following arguments:

ArgumentRequiredDefaultDescription
disabledNoFalseWhen True, all Ampli Wrapper calls are no-ops. Useful in local or development environments.
clientNoNoneA LoadClientOptions instance that specifies configuration options for the Amplitude core SDK client.

LoadClientOptions accepts the following arguments:

ArgumentRequiredDefaultDescription
instanceRequired if api_key isn't setNoneThe Amplitude instance to use. By default, Ampli creates an instance.
api_keyRequired if instance isn't setNoneThe API key to use. Overrides the API key configured in your tracking plan.
configurationNoNoneThe 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:

python
ampli.identify("user_id", Identify(role="admin"))

The options argument accepts Amplitude fields for this call, such as device_id.

python
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:

python
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.

python
ampli.set_group("user_id", "sport", "football")

group_name accepts a single group name string or a list of multiple group names.

python
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:

python
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):

python
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.

python
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.

python
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:

python
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:

python
ampli.client.add(SegmentPlugin("write_key"))

Status

Verify that your code implements events with the status command:

bash
ampli status [--update]

The output displays status and indicates what events are missing.

bash
 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:

python
from ampli import *

Or if your Ampli wrapper is in a package:

python
from your_package.ampli import *

Option 2: Run as a module

Run your script as a module:

bash
python3 -m your_package.main

Was this helpful?