Skip to content

Commit ee1ab75

Browse files
authored
Use future annotations (#107)
1 parent a9c220b commit ee1ab75

39 files changed

+191
-149
lines changed

ansq/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from .tcp.connection import ConnectionFeatures, ConnectionOptions, open_connection
24
from .tcp.reader import create_reader
35
from .tcp.writer import create_writer

ansq/http/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from .lookupd import NsqLookupd
24
from .writer import NSQDHTTPWriter
35

ansq/http/base.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import annotations
2+
13
import asyncio
24
import json
3-
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar
5+
from typing import TYPE_CHECKING, Any, TypeVar
46

57
import aiohttp
68

@@ -24,7 +26,7 @@ def __init__(
2426
host: str = "127.0.0.1",
2527
port: int = 4151,
2628
*,
27-
loop: Optional["AbstractEventLoop"] = None,
29+
loop: AbstractEventLoop | None = None,
2830
) -> None:
2931
self._loop = loop or asyncio.get_event_loop()
3032
self._endpoint = (host, port)
@@ -34,9 +36,9 @@ def __init__(
3436

3537
@classmethod
3638
def from_address(
37-
cls: Type[_T],
39+
cls: type[_T],
3840
address: str,
39-
loop: Optional["AbstractEventLoop"] = None,
41+
loop: AbstractEventLoop | None = None,
4042
) -> _T:
4143
try:
4244
host, port_str = address.split(":")

ansq/http/http_exceptions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Dict
1+
from __future__ import annotations
22

33

44
class NSQHTTPException(Exception):
@@ -19,7 +19,7 @@ def error(self) -> str:
1919
return self.args[1]
2020

2121
@property
22-
def info(self) -> Dict:
22+
def info(self) -> dict:
2323
"""Dict of returned error info from ES, where available."""
2424
return self.args[2]
2525

ansq/http/lookupd.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from ansq.typedefs import HTTPResponse
24

35
from .base import NSQHTTPConnection

ansq/http/writer.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from typing import Any
24

35
from ansq.typedefs import HTTPResponse

ansq/tcp/connection.py

+17-15
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
from __future__ import annotations
2+
13
import asyncio
24
import json
35
import warnings
46
from datetime import datetime, timezone
5-
from typing import Any, AsyncGenerator, Callable, Mapping, Optional, Union
7+
from typing import Any, AsyncGenerator, Callable, Mapping
68

79
import attr
810

@@ -124,7 +126,7 @@ async def _do_auto_reconnect(
124126

125127
async def _do_close(
126128
self,
127-
error: Optional[Union[Exception, str]] = None,
129+
error: Exception | str | None = None,
128130
change_status: bool = True,
129131
silent: bool = False,
130132
) -> None:
@@ -196,10 +198,10 @@ async def _do_close(
196198

197199
async def execute(
198200
self,
199-
command: Union[str, bytes],
201+
command: str | bytes,
200202
*args: Any,
201-
data: Optional[Any] = None,
202-
callback: Optional[Callable[[TCPResponse], Any]] = None,
203+
data: Any | None = None,
204+
callback: Callable[[TCPResponse], Any] | None = None,
203205
) -> TCPResponse:
204206
"""Execute command
205207
@@ -263,9 +265,9 @@ async def execute(
263265

264266
async def identify(
265267
self,
266-
config: Optional[Union[dict, str]] = None,
268+
config: dict | str | None = None,
267269
*,
268-
features: Optional[ConnectionFeatures] = None,
270+
features: ConnectionFeatures | None = None,
269271
**kwargs: Any,
270272
) -> TCPResponse:
271273
"""Executes `IDENTIFY` command.
@@ -362,7 +364,7 @@ async def _read_data_task(self) -> None:
362364
"""Response reader task."""
363365
assert self._reader is not None
364366

365-
error: Optional[Exception] = None
367+
error: Exception | None = None
366368

367369
while not self._reader.at_eof():
368370
try:
@@ -461,10 +463,10 @@ async def _read_buffer(self) -> None:
461463
while is_continue:
462464
is_continue = await self._parse_data()
463465

464-
def _start_upgrading(self, resp: Optional[TCPResponse] = None) -> None:
466+
def _start_upgrading(self, resp: TCPResponse | None = None) -> None:
465467
self._is_upgrading = True
466468

467-
async def _finish_upgrading(self, resp: Optional[TCPResponse] = None) -> None:
469+
async def _finish_upgrading(self, resp: TCPResponse | None = None) -> None:
468470
await self._read_buffer()
469471
self._is_upgrading = False
470472

@@ -522,13 +524,13 @@ async def rdy(self, messages_count: int = 1) -> None:
522524
self.rdy_messages_count = messages_count
523525
await self.execute(NSQCommands.RDY, messages_count)
524526

525-
async def fin(self, message_id: Union[str, NSQMessage]) -> None:
527+
async def fin(self, message_id: str | NSQMessage) -> None:
526528
"""Finish a message (indicate successful processing)"""
527529
if isinstance(message_id, NSQMessage):
528530
await message_id.fin()
529531
await self.execute(NSQCommands.FIN, message_id)
530532

531-
async def req(self, message_id: Union[str, NSQMessage], timeout: int = 0) -> None:
533+
async def req(self, message_id: str | NSQMessage, timeout: int = 0) -> None:
532534
"""Re-queue a message (indicate failure to process)
533535
534536
The re-queued message is placed at the tail of the queue,
@@ -538,7 +540,7 @@ async def req(self, message_id: Union[str, NSQMessage], timeout: int = 0) -> Non
538540
await message_id.req(timeout)
539541
await self.execute(NSQCommands.REQ, message_id, timeout)
540542

541-
async def touch(self, message_id: Union[str, NSQMessage]) -> None:
543+
async def touch(self, message_id: str | NSQMessage) -> None:
542544
"""Reset the timeout for an in-flight message"""
543545
if isinstance(message_id, NSQMessage):
544546
await message_id.touch()
@@ -570,7 +572,7 @@ async def messages(self) -> AsyncGenerator[NSQMessage, None]:
570572
continue
571573
yield message
572574

573-
def get_message(self) -> Optional[NSQMessage]:
575+
def get_message(self) -> NSQMessage | None:
574576
"""Shortcut for ``asyncio.Queue.get_nowait()``
575577
without raising exceptions
576578
"""
@@ -579,7 +581,7 @@ def get_message(self) -> Optional[NSQMessage]:
579581
except asyncio.QueueEmpty:
580582
return None
581583

582-
async def wait_for_message(self) -> Optional[NSQMessage]:
584+
async def wait_for_message(self) -> NSQMessage | None:
583585
"""Shortcut for `asyncio.Queue.get()``.
584586
585587
:rtype: :class:`NSQMessage`

ansq/tcp/consts.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
NL = b"\n"
24
DATA_SIZE = 4
35
FRAME_SIZE = 4

ansq/tcp/exceptions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Union
1+
from __future__ import annotations
22

33

44
class ConnectionClosedError(Exception):
@@ -132,5 +132,5 @@ class NSQTouchFailed(NSQErrorCode):
132132
# E_FIN_FAILED
133133

134134

135-
def get_exception(code: str, error_message: Union[str, bytes]) -> NSQException:
135+
def get_exception(code: str, error_message: str | bytes) -> NSQException:
136136
return ERROR_CODES.get(code, NSQErrorCode)(f"{code}: {error_message!r}")

ansq/tcp/protocol.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
33
:see: https://nsq.io/clients/tcp_protocol_spec.html
44
"""
5+
from __future__ import annotations
6+
57
import abc
68
import struct
7-
from typing import Any, Optional, Tuple, Union
9+
from typing import Any
810

911
from ansq.tcp import consts
1012
from ansq.tcp.exceptions import ProtocolError
@@ -29,12 +31,12 @@ def get(self) -> Any:
2931
pass
3032

3133
@abc.abstractmethod # pragma: no cover
32-
def encode_command(self, cmd: str, *args: Any, data: Optional[Any] = None) -> bytes:
34+
def encode_command(self, cmd: str, *args: Any, data: Any | None = None) -> bytes:
3335
pass
3436

3537

3638
class Reader(BaseReader):
37-
def __init__(self, buffer: Optional[bytes] = None):
39+
def __init__(self, buffer: bytes | None = None):
3840
self._buffer = bytearray()
3941
self._is_header = False
4042
self._payload_size = 0
@@ -57,7 +59,7 @@ def feed(self, chunk: bytes) -> None:
5759

5860
def get(
5961
self,
60-
) -> Optional[Union[NSQResponseSchema, NSQErrorSchema, NSQMessageSchema]]:
62+
) -> NSQResponseSchema | NSQErrorSchema | NSQMessageSchema | None:
6163
"""Get from buffer NSQ response
6264
6365
:raises ProtocolError: On unexpected NSQ message's FrameType
@@ -86,7 +88,7 @@ def get(
8688

8789
def _parse_payload(
8890
self, frame_type: FrameType, payload_size: int
89-
) -> Union[NSQResponseSchema, NSQErrorSchema, NSQMessageSchema]:
91+
) -> NSQResponseSchema | NSQErrorSchema | NSQMessageSchema:
9092
"""Parse from buffer NSQ response
9193
9294
:raises ProtocolError: On unexpected NSQ message's FrameType
@@ -114,13 +116,13 @@ def _unpack_response(self, payload_size: int) -> bytes:
114116
end = consts.DATA_SIZE + payload_size
115117
return bytes(self._buffer[start:end])
116118

117-
def _unpack_error(self, payload_size: int) -> Tuple[bytes, bytes]:
119+
def _unpack_error(self, payload_size: int) -> tuple[bytes, bytes]:
118120
"""Unpack the error from the buffer"""
119121
error = self._unpack_response(payload_size)
120122
code, msg = error.split(maxsplit=1)
121123
return code, msg
122124

123-
def _unpack_message(self, payload_size: int) -> Tuple[int, int, bytes, bytes]:
125+
def _unpack_message(self, payload_size: int) -> tuple[int, int, bytes, bytes]:
124126
"""Unpack the message from the buffer.
125127
126128
:see: https://docs.python.org/3/library/struct.html
@@ -135,9 +137,7 @@ def _unpack_message(self, payload_size: int) -> Tuple[int, int, bytes, bytes]:
135137
timestamp, attempts, id_, body = struct.unpack(fmt, self._buffer[start:end])
136138
return timestamp, attempts, id_, body
137139

138-
def encode_command(
139-
self, cmd: Union[str, bytes], *args: Any, data: Any = None
140-
) -> bytes:
140+
def encode_command(self, cmd: str | bytes, *args: Any, data: Any = None) -> bytes:
141141
"""Encode command to bytes"""
142142
_cmd = convert_to_bytes(cmd.upper().strip())
143143
_args = [convert_to_bytes(a) for a in args]

0 commit comments

Comments
 (0)