Skip to content

Commit 29aded1

Browse files
authored
Merge pull request #1648 from minrk/more-types
More type coverage
2 parents ab72e55 + 2dc67d5 commit 29aded1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+1019
-436
lines changed

examples/asyncio/coroutines.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@
1313
ctx = Context.instance()
1414

1515

16-
async def ping():
16+
async def ping() -> None:
1717
"""print dots to indicate idleness"""
1818
while True:
1919
await asyncio.sleep(0.5)
2020
print('.')
2121

2222

23-
async def receiver():
23+
async def receiver() -> None:
2424
"""receive messages with polling"""
2525
pull = ctx.socket(zmq.PULL)
2626
pull.connect(url)
@@ -34,7 +34,7 @@ async def receiver():
3434
print('recvd', msg)
3535

3636

37-
async def sender():
37+
async def sender() -> None:
3838
"""send a message every second"""
3939
tic = time.time()
4040
push = ctx.socket(zmq.PUSH)

examples/asyncio/helloworld_pubsub_dealerrouter.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,18 @@
1212
import logging
1313
import traceback
1414

15+
import zmq
1516
import zmq.asyncio
1617
from zmq.asyncio import Context
1718

1819

1920
# set message based on language
2021
class HelloWorld:
21-
def __init__(self):
22+
def __init__(self) -> None:
2223
self.lang = 'eng'
2324
self.msg = "Hello World"
2425

25-
def change_language(self):
26+
def change_language(self) -> None:
2627
if self.lang == 'eng':
2728
self.lang = 'jap'
2829
self.msg = "Hello Sekai"
@@ -31,21 +32,21 @@ def change_language(self):
3132
self.lang = 'eng'
3233
self.msg = "Hello World"
3334

34-
def msg_pub(self):
35+
def msg_pub(self) -> str:
3536
return self.msg
3637

3738

3839
# receives "Hello World" from topic 'world'
3940
# changes "World" to "Sekai" and returns message 'sekai'
4041
class HelloWorldPrinter:
4142
# process received message
42-
def msg_sub(self, msg):
43+
def msg_sub(self, msg: str) -> None:
4344
print(f"message received world: {msg}")
4445

4546

4647
# manages message flow between publishers and subscribers
4748
class HelloWorldMessage:
48-
def __init__(self, url='127.0.0.1', port='5555'):
49+
def __init__(self, url: str = '127.0.0.1', port: int = 5555):
4950
# get ZeroMQ version
5051
print("Current libzmq version is %s" % zmq.zmq_version())
5152
print("Current pyzmq version is %s" % zmq.__version__)
@@ -57,6 +58,8 @@ def __init__(self, url='127.0.0.1', port='5555'):
5758
# init hello world publisher obj
5859
self.hello_world = HelloWorld()
5960

61+
def main(self) -> None:
62+
6063
# activate publishers / subscribers
6164
asyncio.get_event_loop().run_until_complete(
6265
asyncio.wait(
@@ -70,7 +73,7 @@ def __init__(self, url='127.0.0.1', port='5555'):
7073
)
7174

7275
# generates message "Hello World" and publish to topic 'world'
73-
async def hello_world_pub(self):
76+
async def hello_world_pub(self) -> None:
7477
pub = self.ctx.socket(zmq.PUB)
7578
pub.connect(self.url)
7679

@@ -106,7 +109,7 @@ async def hello_world_pub(self):
106109
pass
107110

108111
# processes message topic 'world'; "Hello World" or "Hello Sekai"
109-
async def hello_world_sub(self):
112+
async def hello_world_sub(self) -> None:
110113
print("Setting up world sub")
111114
obj = HelloWorldPrinter()
112115
# setup subscriber
@@ -120,7 +123,7 @@ async def hello_world_sub(self):
120123
# keep listening to all published message on topic 'world'
121124
while True:
122125
[topic, msg] = await sub.recv_multipart()
123-
print(f"world sub; topic: {topic}\tmessage: {msg}")
126+
print(f"world sub; topic: {topic.decode()}\tmessage: {msg.decode()}")
124127
# process message
125128
obj.msg_sub(msg.decode('utf-8'))
126129

@@ -141,7 +144,7 @@ async def hello_world_sub(self):
141144
pass
142145

143146
# Deal a message to topic 'lang' that language should be changed
144-
async def lang_changer_dealer(self):
147+
async def lang_changer_dealer(self) -> None:
145148
# setup dealer
146149
deal = self.ctx.socket(zmq.DEALER)
147150
deal.setsockopt(zmq.IDENTITY, b'lang_dealer')
@@ -176,7 +179,7 @@ async def lang_changer_dealer(self):
176179
pass
177180

178181
# changes Hello xxx message when a command is received from topic 'lang'; keeps listening for commands
179-
async def lang_changer_router(self):
182+
async def lang_changer_router(self) -> None:
180183
# setup router
181184
rout = self.ctx.socket(zmq.ROUTER)
182185
rout.bind(self.url[:-1] + f"{int(self.url[-1]) + 1}")
@@ -188,7 +191,9 @@ async def lang_changer_router(self):
188191
# keep listening to all published message on topic 'world'
189192
while True:
190193
[id_dealer, msg] = await rout.recv_multipart()
191-
print(f"Command rout; Sender ID: {id_dealer};\tmessage: {msg}")
194+
print(
195+
f"Command rout; Sender ID: {id_dealer!r};\tmessage: {msg.decode()}"
196+
)
192197

193198
self.hello_world.change_language()
194199
print(
@@ -208,5 +213,10 @@ async def lang_changer_router(self):
208213
pass
209214

210215

216+
def main() -> None:
217+
hello_world = HelloWorldMessage()
218+
hello_world.main()
219+
220+
211221
if __name__ == '__main__':
212-
HelloWorldMessage()
222+
main()

examples/asyncio/tornado_asyncio.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,32 @@
55
import asyncio
66

77
from tornado.ioloop import IOLoop
8-
from tornado.platform.asyncio import AsyncIOMainLoop
98

109
import zmq.asyncio
1110

12-
# Tell tornado to use asyncio
13-
AsyncIOMainLoop().install()
1411

15-
# This must be instantiated after the installing the IOLoop
16-
queue = asyncio.Queue() # type: ignore
17-
ctx = zmq.asyncio.Context()
18-
19-
20-
async def pushing():
21-
server = ctx.socket(zmq.PUSH)
12+
async def pushing() -> None:
13+
server = zmq.asyncio.Context.instance().socket(zmq.PUSH)
2214
server.bind('tcp://*:9000')
2315
while True:
2416
await server.send(b"Hello")
2517
await asyncio.sleep(1)
2618

2719

28-
async def pulling():
29-
client = ctx.socket(zmq.PULL)
20+
async def pulling() -> None:
21+
client = zmq.asyncio.Context.instance().socket(zmq.PULL)
3022
client.connect('tcp://127.0.0.1:9000')
3123
while True:
3224
greeting = await client.recv()
3325
print(greeting)
3426

3527

36-
def zmq_tornado_loop():
28+
def main() -> None:
3729
loop = IOLoop.current()
3830
loop.spawn_callback(pushing)
3931
loop.spawn_callback(pulling)
4032
loop.start()
4133

4234

4335
if __name__ == '__main__':
44-
zmq_tornado_loop()
36+
main()

examples/chat/display.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,12 @@
1717
#
1818
# You should have received a copy of the Lesser GNU General Public License
1919
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20+
from typing import List
2021

2122
import zmq
2223

2324

24-
def main(addrs):
25+
def main(addrs: List[str]):
2526

2627
context = zmq.Context()
2728
socket = context.socket(zmq.SUB)

examples/chat/prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import zmq
2222

2323

24-
def main(addr, who):
24+
def main(addr: str, who: str):
2525

2626
ctx = zmq.Context()
2727
socket = ctx.socket(zmq.PUB)

examples/cython/example.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import zmq
88

99

10-
def python_sender(url, n):
10+
def python_sender(url: str, n: int) -> None:
1111
"""Use entirely high-level Python APIs to send messages"""
1212
ctx = zmq.Context()
1313
s = ctx.socket(zmq.PUSH)
@@ -23,7 +23,7 @@ def python_sender(url, n):
2323
s.send(buf)
2424

2525

26-
def main():
26+
def main() -> None:
2727
import argparse
2828

2929
parser = argparse.ArgumentParser(description="send & recv messages with Cython")

examples/draft/radio-dish.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@
1313

1414
for i in range(10):
1515
time.sleep(0.1)
16-
radio.send(b'%03i' % i, group='numbers')
16+
radio.send(f'{i:03}'.encode('ascii'), group='numbers')
1717
try:
1818
msg = dish.recv(copy=False)
1919
except zmq.Again:
2020
print('missed a message')
2121
continue
22-
print("Received {}:{}".format(msg.group, msg.bytes.decode('utf8')))
22+
print(f"Received {msg.group}:{msg.bytes.decode('utf8')}")
2323

2424
dish.close()
2525
radio.close()

examples/eventloop/asyncweb.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from zmq.eventloop.future import Context as FutureContext
2121

2222

23-
def slow_responder():
23+
def slow_responder() -> None:
2424
"""thread for slowly responding to replies."""
2525
ctx = zmq.Context()
2626
socket = ctx.socket(zmq.ROUTER)
@@ -35,14 +35,14 @@ def slow_responder():
3535
i += 1
3636

3737

38-
def dot():
38+
def dot() -> None:
3939
"""callback for showing that IOLoop is still responsive while we wait"""
4040
sys.stdout.write('.')
4141
sys.stdout.flush()
4242

4343

4444
class TestHandler(web.RequestHandler):
45-
async def get(self):
45+
async def get(self) -> None:
4646
ctx = FutureContext.instance()
4747
s = ctx.socket(zmq.DEALER)
4848

@@ -56,7 +56,7 @@ async def get(self):
5656
self.write(reply)
5757

5858

59-
def main():
59+
def main() -> None:
6060
worker = threading.Thread(target=slow_responder)
6161
worker.daemon = True
6262
worker.start()

examples/eventloop/echostream.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
#!/usr/bin/env python
22
"""Adapted echo.py to put the send in the event loop using a ZMQStream.
33
"""
4+
from typing import List
5+
6+
from tornado import ioloop
47

58
import zmq
6-
from zmq.eventloop import ioloop, zmqstream
9+
from zmq.eventloop import zmqstream
710

8-
loop = ioloop.IOLoop.instance()
11+
loop = ioloop.IOLoop.current()
912

1013
ctx = zmq.Context()
1114
s = ctx.socket(zmq.ROUTER)
1215
s.bind('tcp://127.0.0.1:5555')
13-
stream = zmqstream.ZMQStream(s, loop)
16+
stream = zmqstream.ZMQStream(s)
1417

1518

16-
def echo(msg):
19+
def echo(msg: List[bytes]):
1720
print(" ".join(map(repr, msg)))
1821
stream.send_multipart(msg)
1922

examples/gevent/poll.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@ def sender():
3434
while msgcnt < 10:
3535
socks = dict(poller.poll())
3636
if receiver1 in socks and socks[receiver1] == zmq.POLLIN:
37-
print("Message from receiver1: %s" % receiver1.recv())
37+
print(f"Message from receiver1: {receiver1.recv()!r}")
3838
msgcnt += 1
3939

4040
if receiver2 in socks and socks[receiver2] == zmq.POLLIN:
41-
print("Message from receiver2: %s" % receiver2.recv())
41+
print(f"Message from receiver2: {receiver2.recv()!r}")
4242
msgcnt += 1
4343

44-
print("%d messages received" % msgcnt)
44+
print(f"{msgcnt} messages received")

0 commit comments

Comments
 (0)