Typing stubs for paho-mqtt
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
-
ModuleNotFoundError: No module named 'paho.mqtt.client'
cause `paho-mqtt` library is not installed, only its type stubs (`types-paho-mqtt`) are present.fixInstall the actual `paho-mqtt` library: `pip install paho-mqtt` -
error: Argument "callback_api_version" to "Client" has incompatible type "Literal[2]"; expected "CallableAPIVersion"
cause You are using `paho-mqtt` version < 2.0.0 (which doesn't have `CallbackAPIVersion.VERSION2` as a valid argument) but your type checker is using stubs that might imply it, or you are explicitly passing an incompatible value.fixThis specific error likely means your `paho-mqtt` is too old for the `CallbackAPIVersion.VERSION2` enum member. Update `paho-mqtt` to 2.0.0 or later, or remove the `callback_api_version` argument if you intend to use 1.x behavior (which is the default in 2.x if not specified). -
error: Incompatible types in assignment (expression has type "Callable[[Client, object, dict, int], None]", variable has type "Callable[[Client, dict, dict, int], None]")
cause This is a common type error when migrating `paho-mqtt` 1.x code to 2.x (or vice-versa with incorrect stubs). The `userdata` parameter in callbacks changed type from `object` to `dict` (for `VERSION2`) and back again, or the order/types of other arguments changed.fixAdjust your callback function signatures to match the `paho-mqtt` version you are using AND the `CallbackAPIVersion` you've specified (if any). For `paho-mqtt < 2.0.0` or `CallbackAPIVersion.VERSION1`, `userdata` is `object`. For `paho-mqtt >= 2.0.0` with `CallbackAPIVersion.VERSION2`, `userdata` is `dict`. -
error: 'MQTTMessage' has no attribute 'topic' (note: perhaps 'topic.decode()'?)
cause In `paho-mqtt` versions before 2.0.0, `msg.topic` and `msg.payload` were `bytes`. In 2.0.0+, `msg.topic` is `str`. If you are using `paho-mqtt >= 2.0.0` and `types-paho-mqtt` stubs for 1.x, the stubs might incorrectly report `topic` as `bytes`.fixIf using `paho-mqtt >= 2.0.0`, you can usually remove `.decode()` from `msg.topic`. For `msg.payload`, it remains `bytes` and needs `.decode()`. If the type checker still complains, it means your stubs are out of date for your `paho-mqtt` version.
Warnings
- gotcha Installing `types-paho-mqtt` only provides type hints; it does not install the `paho-mqtt` library itself. You must install both packages for your code to run.
- breaking The current `types-paho-mqtt` version `1.6.0.20240321` is designed for `paho-mqtt` version 1.x. It is NOT fully compatible with `paho-mqtt` version 2.0.0 and later, which introduced significant breaking changes to callback signatures (`on_message`, `on_connect`, etc.) and `MQTTMessage` attributes (e.g., `topic` is now `str` instead of `bytes`).
- gotcha Type checkers (like MyPy) need to be configured correctly to discover and use installed stub files. Ensure your `mypy.ini` (or equivalent) does not exclude your project's virtual environment or site-packages from analysis.
- gotcha There might be slight discrepancies or incompleteness in typing stubs for edge cases or very recent `paho-mqtt` features, especially if the `paho-mqtt` library updates rapidly and the typeshed stubs haven't caught up.
Install
-
pip install paho-mqtt types-paho-mqtt
Imports
- Client
from types_paho_mqtt import Client
import paho.mqtt.client as mqtt client: mqtt.Client
- MQTTMessage
import paho.mqtt.client as mqtt def on_message(client: mqtt.Client, userdata: object, msg: mqtt.MQTTMessage): ...
Quickstart
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}")