Typing stubs for paho-mqtt

1.6.0.20240321 · active · verified Thu Apr 16

This library provides PEP 561 compliant typing stubs for the `paho-mqtt` client library, enabling static type checking tools like MyPy to verify correct usage of `paho-mqtt` APIs. It is part of the `typeshed` project, which centrally maintains type hints for many popular Python packages. The current version, `1.6.0.20240321`, corresponds to `paho-mqtt` version 1.6.0. As a typeshed package, it updates periodically as the upstream library changes or as typeshed contributors enhance the stubs.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates basic `paho-mqtt` client usage with type hints, showing how `types-paho-mqtt` is used by a type checker. It connects to a public test broker, subscribes to a topic, publishes a message, and then disconnects. Note the type annotations for `client`, `userdata`, `flags`, `rc`, and `msg`.

import paho.mqtt.client as mqtt
import time
import os

# Callbacks for paho-mqtt < 2.0.0 or CallbackAPIVersion.VERSION1
def on_connect(client: mqtt.Client, userdata: object, flags: dict, rc: int) -> None:
    if rc == 0:
        print(f"Connected to MQTT Broker! Result code: {rc}")
        client.subscribe("test/topic")
    else:
        print(f"Failed to connect, return code {rc}\n")

def on_message(client: mqtt.Client, userdata: object, msg: mqtt.MQTTMessage) -> None:
    print(f"Received `{msg.payload.decode()}` from `{msg.topic.decode()}`")

# Initialize the MQTT Client (assumes paho-mqtt < 2.0.0 for this stub version)
client: mqtt.Client = mqtt.Client() # Default to paho-mqtt 1.x behavior
client.on_connect = on_connect
client.on_message = on_message

# Connect to a public test broker. For production, use a secure connection to your own broker.
try:
    print("Attempting to connect to test.mosquitto.org:1883")
    client.connect("test.mosquitto.org", 1883, 60)
    client.loop_start() # Start a non-blocking loop

    # Publish a message
    print("Publishing a test message...")
    client.publish("test/topic", "Hello from types-paho-mqtt example!", qos=1)
    time.sleep(5) # Give some time for messages to be processed

    client.loop_stop()
    client.disconnect()
    print("Disconnected from broker.")

except Exception as e:
    print(f"An error occurred during MQTT operations: {e}")

view raw JSON →