0
# PyZMQ
1
2
Python bindings for ZeroMQ (ØMQ), a lightweight and fast messaging library. PyZMQ enables Python applications to use ZeroMQ's high-performance asynchronous messaging patterns including request-reply, publish-subscribe, push-pull, and dealer-router patterns. It supports both CPython and PyPy implementations and provides comprehensive async/await support for modern Python applications.
3
4
## Package Information
5
6
- **Package Name**: pyzmq
7
- **Language**: Python
8
- **Installation**: `pip install pyzmq`
9
- **Version**: 27.0.2
10
11
## Core Imports
12
13
```python
14
import zmq
15
```
16
17
For async support:
18
19
```python
20
import zmq.asyncio
21
```
22
23
## Basic Usage
24
25
```python
26
import zmq
27
28
# Create context and socket for publisher
29
context = zmq.Context()
30
socket = context.socket(zmq.PUB)
31
socket.bind("tcp://*:5555")
32
33
# Send messages
34
for i in range(10):
35
socket.send_string(f"Hello World {i}")
36
37
# Clean up
38
socket.close()
39
context.term()
40
```
41
42
Context manager usage:
43
44
```python
45
import zmq
46
47
# Using context manager for automatic cleanup
48
with zmq.Context() as context:
49
with context.socket(zmq.REQ) as socket:
50
socket.connect("tcp://localhost:5555")
51
socket.send_string("Hello")
52
message = socket.recv_string()
53
print(f"Received: {message}")
54
```
55
56
## Architecture
57
58
PyZMQ provides multiple layers of abstraction:
59
60
- **Backend**: Low-level Cython/CFFI bindings to libzmq C library
61
- **Sugar**: High-level Python wrappers with context managers and convenient methods
62
- **AsyncIO**: Native async/await support integrated with Python's event loop
63
- **Constants**: ZMQ socket types, options, and error codes as Python enums
64
- **Authentication**: ZAP (ZMQ Authentication Protocol) support with certificate management
65
- **Devices**: Background proxy and queue devices for message routing
66
- **Utilities**: JSON API, Z85 encoding, monitoring, and platform-specific helpers
67
68
## Capabilities
69
70
### Core Messaging
71
72
The fundamental Context and Socket classes that form the foundation of all ZMQ communication patterns. Includes synchronous and asynchronous messaging with support for all ZMQ socket types.
73
74
```python { .api }
75
class Context:
76
def socket(self, socket_type: int) -> Socket: ...
77
def term(self) -> None: ...
78
79
class Socket:
80
def bind(self, address: str) -> None: ...
81
def connect(self, address: str) -> None: ...
82
def send(self, data: bytes, flags: int = 0) -> None: ...
83
def recv(self, flags: int = 0) -> bytes: ...
84
def send_string(self, string: str, flags: int = 0, encoding: str = 'utf-8') -> None: ...
85
def recv_string(self, flags: int = 0, encoding: str = 'utf-8') -> str: ...
86
```
87
88
[Core Messaging](./core-messaging.md)
89
90
### Asynchronous Programming
91
92
Native async/await support with AsyncIO-compatible Context, Socket, and Poller classes that integrate seamlessly with Python's event loop for non-blocking messaging operations.
93
94
```python { .api }
95
class Context:
96
def socket(self, socket_type: int) -> Socket: ...
97
98
class Socket:
99
async def send(self, data: bytes, flags: int = 0) -> None: ...
100
async def recv(self, flags: int = 0) -> bytes: ...
101
async def send_string(self, string: str, flags: int = 0, encoding: str = 'utf-8') -> None: ...
102
async def recv_string(self, flags: int = 0, encoding: str = 'utf-8') -> str: ...
103
```
104
105
[Async Support](./async-support.md)
106
107
### Message Handling
108
109
Zero-copy message objects (Frame/Message) for efficient data transfer, with support for metadata, copying control, and memory-mapped operations.
110
111
```python { .api }
112
class Frame:
113
def __init__(self, data: bytes = b'', track: bool = True) -> None: ...
114
@property
115
def bytes(self) -> bytes: ...
116
def copy(self) -> Frame: ...
117
118
class Message(Frame):
119
def get(self, property: int) -> int: ...
120
def set(self, property: int, value: int) -> None: ...
121
```
122
123
[Message Handling](./message-handling.md)
124
125
### Event Polling
126
127
High-performance event polling for monitoring multiple sockets simultaneously, with support for timeouts and different polling backends.
128
129
```python { .api }
130
class Poller:
131
def register(self, socket: Socket, flags: int = POLLIN | POLLOUT) -> None: ...
132
def unregister(self, socket: Socket) -> None: ...
133
def poll(self, timeout: int = -1) -> list[tuple[Socket, int]]: ...
134
135
def select(rlist: list, wlist: list, xlist: list, timeout: float = None) -> tuple: ...
136
```
137
138
[Polling](./polling.md)
139
140
### Authentication & Security
141
142
ZAP (ZMQ Authentication Protocol) implementation with support for NULL, PLAIN, and CURVE security mechanisms, including certificate generation and management.
143
144
```python { .api }
145
class Authenticator:
146
def configure_plain(self, domain: str = '*', passwords: dict = None) -> None: ...
147
def configure_curve(self, domain: str = '*', location: str = '') -> None: ...
148
149
def curve_keypair() -> tuple[bytes, bytes]: ...
150
def curve_public(secret_key: bytes) -> bytes: ...
151
```
152
153
[Authentication](./authentication.md)
154
155
### Devices & Proxying
156
157
Background devices for message routing including proxy, queue, forwarder, and steerable proxy implementations with monitoring capabilities.
158
159
```python { .api }
160
def proxy(frontend: Socket, backend: Socket, capture: Socket = None) -> None: ...
161
def proxy_steerable(frontend: Socket, backend: Socket, capture: Socket = None, control: Socket = None) -> None: ...
162
163
class ThreadDevice:
164
def start(self) -> None: ...
165
def join(self, timeout: float = None) -> None: ...
166
```
167
168
[Devices](./devices.md)
169
170
### Constants & Configuration
171
172
Comprehensive constants for socket types, options, events, and error codes, organized as Python enums for type safety and IDE support.
173
174
```python { .api }
175
class SocketType(IntEnum):
176
PAIR: int
177
PUB: int
178
SUB: int
179
REQ: int
180
REP: int
181
DEALER: int
182
ROUTER: int
183
PULL: int
184
PUSH: int
185
186
class SocketOption(IntEnum):
187
AFFINITY: int
188
ROUTING_ID: int
189
SUBSCRIBE: int
190
UNSUBSCRIBE: int
191
RATE: int
192
RECOVERY_IVL: int
193
```
194
195
[Constants](./constants.md)
196
197
### Error Handling
198
199
Exception hierarchy for ZMQ-specific errors with errno mapping, context information, and specialized exceptions for different error conditions.
200
201
```python { .api }
202
class ZMQError(Exception):
203
errno: int
204
strerror: str
205
206
class ZMQBindError(ZMQError): ...
207
class ZMQVersionError(ZMQError): ...
208
class NotDone(ZMQError): ...
209
```
210
211
[Error Handling](./error-handling.md)
212
213
### Version Information
214
215
Functions for retrieving PyZMQ and libzmq version information.
216
217
```python { .api }
218
def pyzmq_version() -> str:
219
"""Return the version of PyZMQ as a string."""
220
221
def pyzmq_version_info() -> tuple[int, int, int] | tuple[int, int, int, float]:
222
"""Return the PyZMQ version as a tuple of at least three numbers."""
223
224
def zmq_version() -> str:
225
"""Return the version of libzmq as a string."""
226
227
def zmq_version_info() -> tuple[int, int, int]:
228
"""Return the libzmq version as a tuple of three integers."""
229
230
__version__: str # PyZMQ version string
231
__revision__: str # Git revision string
232
```
233
234
### Utility Functions
235
236
Helper functions for building and linking against PyZMQ.
237
238
```python { .api }
239
def get_includes() -> list[str]:
240
"""Return directories to include for linking against PyZMQ with Cython."""
241
242
def get_library_dirs() -> list[str]:
243
"""Return directories used to link against PyZMQ's bundled libzmq."""
244
245
def has(capability: str) -> bool:
246
"""Check if libzmq has a specific capability (curve, ipc, pgm, etc.)."""
247
248
def strerror(errno: int) -> str:
249
"""Return error string for given ZMQ errno."""
250
251
def zmq_errno() -> int:
252
"""Return the current ZMQ errno."""
253
254
# Important constants
255
COPY_THRESHOLD: int # Copy threshold for message handling (65536)
256
DRAFT_API: bool # True if draft API features are available
257
IPC_PATH_MAX_LEN: int # Maximum length for IPC socket paths
258
```
259
260
## Types
261
262
```python { .api }
263
from typing import Union, Optional, Any, Callable
264
265
# Common type aliases
266
SocketType = int
267
Address = str
268
Data = Union[bytes, str, memoryview, Frame]
269
Flags = int
270
Timeout = int
271
MessageTracker = Any # Message tracking object
272
Frame = Any # ZMQ frame object for zero-copy operations
273
```