---
source_url: https://www.pubnub.com/docs/sdks/asyncio/api-reference/subscribe
title: Subscribe API for Python-Asyncio SDK
updated_at: 2026-11-25T12:28:11.000Z
sdk_name: PubNub Python Asyncio SDK
sdk_version: 10.9.1
description: "Reference for the subscribe methods of the PubNub Python-Asyncio SDK: subscriptions, subscription sets, SDK entities, event listeners, and unsubscribing, with parameters and sample code."
---

# Subscribe API for Python-Asyncio SDK

PubNub Python Asyncio SDK, use the latest version: 10.9.1

Install:

```bash
pip install pubnub==10.9.1
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

The Subscribe API lets a PubNub client for Python-Asyncio SDK receive messages and events in real time. You create a subscription for one SDK entity, or a subscription set for several, add an event listener, and then subscribe.

For the concepts behind publishing and subscribing, see [Connection management](https://www.pubnub.com/docs/architecture/connection-management/overview.md), [Subscriptions](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md), and [Publish messages](https://www.pubnub.com/docs/pub-sub/publish/overview.md). The methods on this page return `None` at once, so they have no `future()` call and you don't await them.

## Subscribe

`subscribe()` starts receiving real-time messages and events for a subscription or subscription set of a PubNub client for Python-Asyncio SDK.

To subscribe, set `subscribe_key` when you create the PubNub client. See [Initialization](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration.md#initialization).

By default, a subscription receives the messages that PubNub publishes after the subscribe request completes. Calling `subscribe()` starts the subscription but delivers nothing to your code until you add an event listener.

A PubNub client for Python-Asyncio SDK retries failed subscribe requests as set by `reconnect_policy`. See [Configuration](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration.md#configuration).

The default subscribe loop of the Python-Asyncio SDK ignores the `filter_expression` setting. Subscribe filters have no effect on this SDK.

### Subscription scope

Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:

* [`subscription`](#create-a-subscription): created from an SDK entity and scoped to that entity, for example a particular channel
* [`subscription_set`](#create-a-subscription-set): created from the PubNub client and scoped to the subscriptions that you put in the set

```mermaid
flowchart TD
    C(Scope of real-time updates)
    C -->|Client scope<br/><code>subscription_set</code>| G[Create a subscription set <br>on the pubnub object]
    C -->|SDK entity scope<br/><code>subscription</code>| D[Create an SDK entity]

    D --> E[Create a subscription<br>on that SDK entity]
    E --> F[Add event listeners]
    F --> H[Subscribe]

    G --> I[Add event listeners]
    I --> J[Subscribe]

    style H fill:#bbf,stroke:#f66,stroke-width:2px,stroke-dasharray: 5, 5
    style J fill:#bbf,stroke:#f66,stroke-width:2px,stroke-dasharray: 5, 5
```

`subscription` and `subscription_set` use the same `subscribe()` method.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| timetoken | Optional[int] | Optional | `None` | The timetoken from which to start returning available cached messages. PubNub provides cached messages on a best-effort basis. The SDK starts receiving from this timetoken. |
| region | Optional[str] | Optional | `None` | The region of an earlier subscribe response. The SDK accepts this value and ignores it. |

A wildcard channel name such as `my_channel.*` subscribes the same way. The message event reports the concrete channel in `channel` and the matching pattern in `subscription`. A message on a channel that matches both a subscribed channel and a subscribed wildcard, such as `my_channel.2` and `my_channel.*`, can reach your listener twice.

### Returns

`subscribe()` returns nothing.

### Examples for Subscribe

#### Syntax

```python
subscription.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None
subscription_set.subscribe(timetoken: Optional[int] = None, region: Optional[str] = None) -> None
```

#### Basic usage

```python
# single channel subscription
channel = pubnub.channel("my_channel")
t1_subscription = channel.subscription()
t1_subscription.subscribe()
```

#### Subscribe a subscription set

The set subscribes to every channel and channel group of its subscriptions with one call.

```python
channel = "my_channel"

# multiple channel subscription
channel_1 = pubnub.channel(channel).subscription()
channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)

group = pubnub.channel_group("group-test").subscription()

subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])

subscription_set.subscribe()
```

## Create a subscription

`subscription()` creates a subscription for one SDK entity of a PubNub client for Python-Asyncio SDK. The subscription receives messages and events for only that entity.

Use several subscriptions to handle the message and event types of each channel differently.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| with_presence | bool | Optional | `None` | Whether the subscription delivers presence events for the entity to its listeners. The value `True` also subscribes to the `-pnpres` channel of the entity and enables the `on_presence` handler. `None` counts as `False`. For the events and how to receive them, see [Presence events](https://www.pubnub.com/docs/presence/presence-events.md). |

### Examples for Create a subscription

#### Syntax

```python
channel.subscription(with_presence: bool = None) -> PubNubSubscription
```

#### Basic usage

```python
def on_presence(listener):
    def presence_callback(presence):
        print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
              f"{presence.subscription or presence.channel}\033[0m")
    return presence_callback

subscription = pubnub.channel("my_channel").subscription(with_presence=True)
subscription.on_presence = on_presence('presence_listener')

subscription.subscribe()
```

## Create a subscription set

`subscription_set()` creates a subscription set in a PubNub client for Python-Asyncio SDK. The set receives messages and events for all the SDK entities that it contains.

Use a subscription set to handle the message and event types of several channels in the same way.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscriptions | List[PubNubSubscription] | Yes | n/a | The subscriptions that the set contains. Create each one with `subscription()` on an SDK entity. The set subscribes to the channels and channel groups of its subscriptions. |

The method takes subscriptions only. The method has no `channels` or `channel_groups` parameter, so it raises `TypeError` for either keyword.

### Examples for Create a subscription set

#### Syntax

```python
pubnub.subscription_set(subscriptions: List[PubNubSubscription]) -> PubNubSubscriptionSet
```

#### Basic usage

```python
channel = "my_channel"

# multiple channel subscription
channel_1 = pubnub.channel(channel).subscription()
channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True)
channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True)

group = pubnub.channel_group("group-test").subscription()

subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group])

subscription_set.subscribe()
```

## SDK entities

An SDK entity is a local handle that represents something you can subscribe to in a PubNub client for Python-Asyncio SDK. Creating one performs no network call and needs no matching server-side record.

Every SDK entity has a `subscription()` method. The client has a creation method for each kind of SDK entity:

* [`channel`](#create-an-sdk-channel-entity)
* [`channel_group`](#create-an-sdk-channel-group-entity)
* [`user_metadata`](#create-an-sdk-user-metadata-entity)
* [`channel_metadata`](#create-an-sdk-channel-metadata-entity)

## Create an SDK channel entity

`channel()` returns an SDK channel entity that represents a channel in a PubNub client for Python-Asyncio SDK.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | The ID of the channel to subscribe to. See [channels](https://www.pubnub.com/docs/pub-sub/subscribe/channels.md). |

### Examples for Create an SDK channel entity

#### Syntax

```python
pubnub.channel(channel: str) -> PubNubChannel
```

#### Basic usage

```python
channel = pubnub.channel("my_channel")
```

## Create an SDK channel group entity

`channel_group()` returns an SDK channel group entity that represents a channel group in a PubNub client for Python-Asyncio SDK.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel_group | str | Yes | n/a | The name of the channel group to subscribe to. See [channel groups](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md). |

### Examples for Create an SDK channel group entity

#### Syntax

```python
pubnub.channel_group(channel_group: str) -> PubNubChannelGroup
```

#### Basic usage

```python
channel_group = pubnub.channel_group("channelGroupName")
```

## Create an SDK channel metadata entity

`channel_metadata()` returns an SDK channel metadata entity that represents the App Context metadata of a channel in a PubNub client for Python-Asyncio SDK.

A subscription to this SDK entity delivers its App Context events to the `on_channel_metadata` handler and to the `channel` method of a `SubscribeCallback` listener. See [Add listeners](#add-listeners).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | The ID of the channel metadata object to observe. See [channel metadata](https://www.pubnub.com/docs/data-storage/metadata/manage-channel-metadata.md). |

### Examples for Create an SDK channel metadata entity

#### Syntax

```python
pubnub.channel_metadata(channel: str) -> PubNubChannelMetadata
```

#### Basic usage

```python
channel_metadata = pubnub.channel_metadata("channelMetadata")
```

## Create an SDK user metadata entity

`user_metadata()` returns an SDK user metadata entity that represents the App Context metadata of a user in a PubNub client for Python-Asyncio SDK.

A subscription to this SDK entity delivers its App Context events to the `on_user_metadata` handler and to the `uuid` method of a `SubscribeCallback` listener. See [Add listeners](#add-listeners).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| user_id | str | Yes | n/a | The ID of the user metadata object to observe. See [user metadata](https://www.pubnub.com/docs/data-storage/metadata/manage-user-metadata.md). |

### Examples for Create an SDK user metadata entity

#### Syntax

```python
pubnub.user_metadata(user_id: str) -> PubNubUserMetadata
```

#### Basic usage

```python
user_metadata = pubnub.user_metadata("user_metadata")
```

## Event listeners

Event listeners are the single point through which your app receives all the messages, signals, and events of a PubNub client for Python-Asyncio SDK.

You can attach listeners to a subscription, a subscription set, and the PubNub client. A listener on the PubNub client receives the events of all its subscriptions. A subscription or subscription set takes handler attributes such as `on_message`, and the PubNub client takes a `SubscribeCallback` object. Attach the connection status listener to the PubNub client only. See [Add connection status listener](#add-connection-status-listener).

:::note No built-in event throttling
The PubNub SDK delivers every incoming event to your listener as it arrives. There is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.
To reduce the number of messages delivered to your client in the first place, use [Subscribe Filters](https://www.pubnub.com/docs/pub-sub/subscribe/subscribe-filter-expressions.md) to filter messages server-side before they reach your listener.
:::

## Add listeners

`add_listener()` adds an event listener that receives messages and events through a subscription, subscription set, or PubNub client for Python-Asyncio SDK.

You can assign an event-specific handler that receives only one type of event, such as `on_message` or `on_signal`. Each assignment replaces the previous handler of that type.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| on_message | Callable[[PNMessageResult], None] | Optional | n/a | Handles published messages. |
| on_signal | Callable[[PNSignalMessageResult], None] | Optional | n/a | Handles signals. |
| on_presence | Callable[[PNPresenceEventResult], None] | Optional | n/a | Handles presence events. A subscription calls it only when you create it with `with_presence=True`. A subscription set never calls it. |
| on_message_action | Callable[[PNMessageActionResult], None] | Optional | n/a | Handles message action events. |
| on_channel_metadata | Callable[[PNChannelMetadataResult], None] | Optional | n/a | Handles channel metadata events. |
| on_user_metadata | Callable[[PNUUIDMetadataResult], None] | Optional | n/a | Handles user metadata events. |
| on_membership | Callable[[PNMembershipResult], None] | Optional | n/a | Handles membership events. |
| on_file | Callable[[PNFileMessageResult], None] | Optional | n/a | Handles file events. |
| listener | SubscribeCallback | Yes | n/a | An object whose methods handle each event type. Only `pubnub.add_listener()` takes it. |
| > status | Callable[[PubNub, PNStatus], None] | Optional | n/a | Handles connection status changes. Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set. See [Add connection status listener](#add-connection-status-listener). |
| > message | Callable[[PubNub, PNMessageResult], None] | Optional | n/a | Handles published messages. |
| > signal | Callable[[PubNub, PNSignalMessageResult], None] | Optional | n/a | Handles signals. |
| > presence | Callable[[PubNub, PNPresenceEventResult], None] | Optional | n/a | Handles presence events. |
| > message_action | Callable[[PubNub, PNMessageActionResult], None] | Optional | n/a | Handles message action events. |

`SubscribeCallback` also declares the methods `channel`, `uuid`, `membership`, and `file`. A subscription or subscription set delivers the App Context and file events of its channels to the `on_channel_metadata`, `on_user_metadata`, `on_membership`, and `on_file` handlers, and to the matching methods of a `SubscribeCallback` listener.

`subscription.add_listener()` takes a `SubscribeCallback` object. The SDK calls its methods with the `pubnub` argument, as it does for `pubnub.add_listener()`.

### Returns

`add_listener()` returns nothing.

### Examples for Add listeners

#### Syntax

```python
subscription.on_message: Callable[[PNMessageResult], None]
subscription.on_signal: Callable[[PNSignalMessageResult], None]
subscription.on_presence: Callable[[PNPresenceEventResult], None]
subscription.on_message_action: Callable[[PNMessageActionResult], None]
subscription.on_channel_metadata: Callable[[PNChannelMetadataResult], None]
subscription.on_user_metadata: Callable[[PNUUIDMetadataResult], None]
subscription.on_membership: Callable[[PNMembershipResult], None]
subscription.on_file: Callable[[PNFileMessageResult], None]
subscription_set.on_message: Callable[[PNMessageResult], None]
subscription_set.on_signal: Callable[[PNSignalMessageResult], None]
subscription_set.on_message_action: Callable[[PNMessageActionResult], None]
pubnub.add_listener(listener: SubscribeCallback) -> None
```

#### Basic usage

```python
subscription = pubnub.channel("my_channel").subscription()

# using closure for reusable listener
def on_message(listener):
    def message_callback(message):
        print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
    return message_callback

# without closure
def on_message_action(message_action):
    print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n")

def on_signal(listener):
    def signal_callback(signal):
        print(f"\033[0;36mSignal received on: {listener}: \n{signal.publisher} says: \t{signal.message}\033[0m")
    return signal_callback

subscription.on_message = on_message('message_listener')
subscription.on_message_action = on_message_action
subscription.on_signal = on_signal('signal_listener')

subscription.subscribe()
```

```python
from pubnub.callbacks import SubscribeCallback

# add generic listener
class PrintListener(SubscribeCallback):
    def status(self, _, status):
        print(f'\033[92mPrintListener.status:\n{status.category.name}\033[0m')

    def message(self, _, message):
        print(f'\033[94mPrintListener.message:\n{message.message}\033[0m')

    def presence(self, _, presence):
        print(f'PrintListener.presence:\n{presence.uuid} {presence.event}s '
              f'{presence.subscription or presence.channel}\033[0m')

    def signal(self, _, signal):
        print(f'PrintListener.signal:\n{signal.message} from {signal.publisher}\033[0m')

    def channel(self, _, channel):
        print(f'\033[0;37mChannel Meta:\n{channel.__dict__}\033[0m')

    def uuid(self, _, uuid):
        print(f'User Meta:\n{uuid.__dict__}\033[0m')

    def membership(self, _, membership):
        print(f'Membership:\n{membership.__dict__}\033[0m')

    def message_action(self, _, message_action):
        print(f'PrintListener.message_action {message_action}\033[0m')

    def file(self, _, file_message):
        print(f' {file_message.__dict__}\033[0m')

# The docs call subscription.add_listener(PrintListener()). The SDK then calls PrintListener.message(message)
# without the pubnub argument and raises TypeError, so the client-level add_listener is used here.
pubnub.add_listener(PrintListener())

subscription = pubnub.channel("my_channel").subscription()
subscription.subscribe()
```

#### Handle messages of a subscription set

```python
def on_message(listener):
    def message_callback(message):
        print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n")
    return message_callback

subscription_set = pubnub.subscription_set([
    pubnub.channel("my_channel").subscription(),
    pubnub.channel("my_channel_2").subscription(),
    pubnub.channel_group("cg_1").subscription()
])
subscription_set.on_message = on_message('set_listener')

subscription_set.subscribe()
```

#### Handle presence events of a subscription

```python
def on_presence(listener):
    def presence_callback(presence):
        print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s "
              f"{presence.subscription or presence.channel}\033[0m")
    return presence_callback

subscription = pubnub.channel("my_channel").subscription(with_presence=True)
subscription.on_presence = on_presence('presence_listener')

subscription.subscribe()
```

## Add connection status listener

`add_listener()` adds a listener that reports the connection status of a PubNub client for Python-Asyncio SDK.

Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| listener | SubscribeCallback | Yes | n/a | An object whose `status()` method the SDK calls each time the connection status changes. |
| > status | Callable[[PubNub, PNStatus], None] | Yes | n/a | The handler that receives the client and the status object described under Returns. |

### Returns

The handler receives a `PNStatus` object. Call `status.is_error()` to check for an error. For the list of status categories, see [SDK statuses](https://www.pubnub.com/docs/sdks/asyncio/status-events.md).

| Property | Type | Description |
| --- | --- | --- |
| category | PNStatusCategory | The status category, for example `PNConnectedCategory`. |
| operation | Optional[PNOperationType] | The operation that reported the status. The value is `None` for the connected status. |
| error | bool | Whether the operation failed. |
| error_data | Optional[PNErrorData] | The details of the error. The value is `None` when `error` is `False`. |
| status_code | None | Always `None` for subscribe statuses. |
| affected_channels | Optional[List[str]] | The channels that the status change affects. The value is `None` unless the status reports a change of subscribed channels. |
| affected_groups | Optional[List[str]] | The channel groups that the status change affects. The value is `None` unless the status reports a change of subscribed channel groups. |

### Examples for Add connection status listener

#### Syntax

```python
pubnub.add_listener(listener: SubscribeCallback) -> None
```

#### Basic usage

```python
from pubnub.pubnub_asyncio import SubscribeListener

class PrintListener(SubscribeListener):
    def status(self, pubnub, status):
        print(f'Status:\n{status.__dict__}')

    def message(self, pubnub, message):
        pass

    def presence(self, pubnub, presence):
        pass

listener = PrintListener()
pubnub.add_listener(listener)
```

## Remove listener

`remove_listener()` removes an event listener from a PubNub client for Python-Asyncio SDK, so the listener stops receiving events.

The SDK identifies a listener by object, so pass the same object that you passed to `add_listener()`. Removing an object that you never added raises `ValueError`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| listener | SubscribeCallback | Yes | n/a | The listener object to remove. Pass the object that you passed to `add_listener()`. |

### Returns

`remove_listener()` returns nothing.

### Examples for Remove listener

#### Syntax

```python
pubnub.remove_listener(listener: SubscribeCallback) -> None
```

#### Basic usage

```python
my_listener = MySubscribeCallback()

pubnub.add_listener(my_listener)

# some time later
pubnub.remove_listener(my_listener)
```

## Unsubscribe

`unsubscribe()` stops a subscription or subscription set of a PubNub client for Python-Asyncio SDK from receiving real-time updates.

A channel stays subscribed while another active subscription or subscription set of the same PubNub client still uses it. If the set subscribed a subscription, `unsubscribe()` on that subscription doesn't stop the channel.

:::warning Subscription sets stay subscribed
`subscription_set.unsubscribe()` doesn't stop the channels of the set. The SDK sends no unsubscribe request for channels that a set subscribed, so the set keeps receiving messages (`pubnub/models/subscription.py:162-182`). To stop those channels, call the [not recommended `unsubscribe()` builder](https://www.pubnub.com/docs/sdks/asyncio/api-reference/subscribe-legacy.md#unsubscribe-old) with the channel names.
:::

`unsubscribe()` takes no parameters.

### Returns

`unsubscribe()` returns nothing. The SDK reports the change to the `status` method of the listeners on the PubNub client. The SDK sends a leave request for the channels unless `suppress_leave_events` is `True`.

### Examples for Unsubscribe

#### Syntax

```python
subscription.unsubscribe() -> None
subscription_set.unsubscribe() -> None
```

#### Basic usage

```python
# single channel subscription
channel = pubnub.channel("my_channel")
t1_subscription = channel.subscription()
t1_subscription.subscribe()
t1_subscription.unsubscribe()
```

## Unsubscribe all

`unsubscribe_all()` unsubscribes every subscription and subscription set of a PubNub client for Python-Asyncio SDK at once.

Only the PubNub client has this method, not a subscription or subscription set.

:::warning Don't await, and subscribe first
`unsubscribe_all()` is a regular method, so don't await it. Before the first `subscribe()`, it does nothing, and `get_subscribed_channels()` returns an empty list.
:::

:::warning The client can't subscribe again
After `unsubscribe_all()`, the SDK can't register new subscriptions on the same PubNub client. The next `subscribe()` raises `TypeError` because the method replaces the internal registry with lists (`pubnub/models/subscription.py:263-271`). Create a new PubNub client to subscribe again.
:::

`unsubscribe_all()` takes no parameters.

### Returns

`unsubscribe_all()` returns nothing.

### Examples for Unsubscribe all

#### Syntax

```python
pubnub.unsubscribe_all() -> None
```

#### Basic usage

```python
pubnub.unsubscribe_all()
```

## Not recommended subscribe methods

`pubnub.subscribe()` and `pubnub.unsubscribe()` of the PubNub Python-Asyncio SDK start and stop subscriptions without a subscription object. Their use is not recommended, and subscriptions replace them.

The builders `pubnub.subscribe()` and `pubnub.unsubscribe()` take `channels` and `channel_groups`. New apps use [Subscribe](#subscribe) and [Unsubscribe](#unsubscribe) with subscriptions instead. The `pubnub.unsubscribe_all()` method is the same current method in both styles. See [Unsubscribe all](#unsubscribe-all). The reference for apps that still use the builders is [Subscribe API: not recommended methods for Python-Asyncio SDK](https://www.pubnub.com/docs/sdks/asyncio/api-reference/subscribe-legacy.md).

Last updated at: 2026-11-25T12:28:11.000Z
