Skip to content

Python Ampli Wrapper

Overview

The Ampli Wrapper is a generated, strongly typed API for tracking Analytics events based on your Tracking Plan in Amplitude Data. The tracking library exposes a function for every event in your team’s tracking plan. The function’s arguments correspond to the event’s properties.

Ampli can benefit your app by providing autocompletion for events & properties defined in Data and enforce your event schemas in code to prevent bad instrumentation.

Amplitude Data supports tracking analytics events from Python apps (Python 3.6 or higher). The generated tracking library is packaged as a python package.

Ampli Python Resources

Basic Python Example · Django Example · Releases

Ampli Wrapper versus the Amplitude SDK

We recommend using the Ampli wrapper for all the benefits mentioned above. However, if you want to send events without creating a tracking plan in Amplitude Data, you can learn more about the underlying Amplitude SDK in our SDK Quickstart Guide. Click here for more documentation on the Amplitude Python SDK.

Deprecated Itly runtime

This page covers the Python Ampli runtimes. All Python Itly runtimes are deprecated. If you are still using an Python Itly runtime, see the migration guide to upgrade to the newest runtime. Docs for the Itly version are available here.

Quick Start

  1. (Prerequisite) Create a Tracking Plan in Amplitude Data

    Plan your events and properties in Amplitude Data. See detailed instructions here

  2. Install the Amplitude SDK

    pip install amplitude-analytics
    
  3. Install the Ampli CLI

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

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

    from .ampli import *
    
    ampli.load(LoadOptions(
      environment=Environment.PRODUCTION
    ))
    
  6. Identify users and set user properties

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

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

    ampli.flush();
    
  9. Verify implementation status with CLI

    ampli status [--update]
    

Installation

Install the Amplitude SDK

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

pip install amplitude-analytics

Install the Ampli CLI

You can install the Ampli CLI from Homebrew or NPM.

brew tap amplitude/ampli
brew install ampli
npm install -g @amplitude/ampli

Pull the Ampli Wrapper into your project

Run the Ampli CLI pull command to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan. Ampli CLI commands are usually run from the project root directory.

ampli pull

API

Load

Initialize Ampli in your code. The load() method requires a configuration options parameter:

from .ampli import *


ampli.load(LoadOptions(
  environment=Environment.PRODUCTION
))
Arg of load()
Description
options Required. An instance of LoadOptions. Specifies configuration options for the Ampli Wrapper.
Arg of LoadOptions
Description
environment Required. String. Specifies the environment the Ampli Wrapper is running in e.g. production or development. Environments can be created, renamed, and managed in Amplitude Data.

Environment determines which API token is used when sending events.

If an client.api_key or client.instance is provided, environment will be ignored, and can be omitted.
disabled Optional. Defaults to False. Specifies whether the Ampli Wrapper does any work. When true, all calls to the Ampli Wrapper are no-ops. Useful in local or development environments.
environment Optional. Defaults to None. Specifies the environment the Ampli Wrapper runs in: either production or development. Environment determines which Access Token is used to load the underlying analytics provider libraries.
client Optional. Defaults to None. A instance of LoadClientOptions specifies configuration options for the Amplitude core SDK client.
Arg of LoadClientOptions
Description
instance Optional. Defaults to None. Specifies an Amplitude instance. By default Ampli creates an instance for you.
api_key Optional. Defaults to None. Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.
configuration Optional. Defaults to None. Specifies the Amplitude configuration. This option overrides the default configuration.

Identify

Call identify() to identify a user in your app and associate all future events with their identity, or to set their properties.

Just as Ampli creates types for events and their properties, it creates types for user properties.

The identify() function accepts a string user_id, an Identify event instance, and an optional EventOptions.

For example your tracking plan contains a user property called role. The property's type is a string.

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

The options argument allows you to pass Amplitude fields for this call, such as device_id.

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

Group Identify

Feature availability

This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.

Call group_identify() to identify a group in your app and set/update group properties.

Just as Ampli creates types for events and their properties, it creates types for group properties.

The group_identify() function accepts a string group_type, a string group_name, an Group event instance, and an optional EventOptions.

For example your tracking plan contains a group sport:football has a property called total_member. The property's type is a int.

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 accept user_id group_type, group_name and an optional EventOptions.

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

group_name can be one group name string or multiple group names list.

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. The call is structured like this:

ampli.event_name("user_id", EventName(...), EventOptions(...))

The optional EventOptions argument allows you to pass Amplitude fields, like device_id.

For example, in the following code snippet, your tracking plan contains an event called songPlayed. The event is defined with two required properties: songId and songFavorited. The property type for songId is string, and songFavorited is a boolean.

ampli.song_played('user_id', SongPlayed(
  song_id = 'songId', # str,
  song_favorited = True, # bool
))

Ampli also generates a class for each event.

my_event = SongPlayed(
  song_id = 'songId', # str,
  song_favorited = True, # bool
)

Send event objects using the generic track method.

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 on an interval based on the configuration.

Call flush() to immediately send any pending events.

The flush() method returns a promise that can be used to ensure all pending events have been sent before continuing. This can be useful to call prior to application exit.

ampli.flush();

Plugin

Plugins allow you to extend the Amplitude behavior, for example, modifying event properties (enrichment type) or sending to a third-party APIs (destination type).

First you need to define your plugin. Destination Plugin example:

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 init Ampli:

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

Ampli CLI

Pull

The pull command downloads the Ampli Wrapper code to your project. Run the pull command from the project root.

ampli pull

You will be prompted 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

Learn more about ampli pull.

Status

Verify that events are implemented in your code 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

Learn more about ampli status.

Migrate from an Itly Python runtime

Migrate from an Itly Python runtime to Ampli by following these steps.

  1. Update Source runtime. In the web app open the Connections > Source modal. From the dropdown, update the source to a non-(Itly) runtime.

  2. Follow steps on this page for detailed setup and usage instructions.

  3. Remove legacy Itly dependencies from your project.

    pip uninstall -r itly/requirements.txt
    rm -rf ./itly
    
  4. Add Amplitude dependencies.

    pip install amplitude-analytics
    
  5. Pull the latest Ampli Wrapper.

    ampli pull
    
  6. Check your Ampli Wrapper path. ampli pull prints the download location of the new SDK. If this still contains itly you can update the Path by hand in the ampli.json file, or pull again using the --path parameter: ampli pull -p ./path/to/ampli.

  7. Find and replace:

    • import itly => from ampli import *
    • itly. => ampli.
  8. See updated Event tracking details on your Implementation page in the web app.


Still have questions? Ask them in the Community.