Skip to content

Commit 88f7529

Browse files
committed
Upgrade syntax with Ruff
1 parent 66452e1 commit 88f7529

16 files changed

+107
-132
lines changed

docs/source/make-state-diagrams.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@
2525
"""
2626

2727
def finish(machine_name):
28-
return ("""
28+
return (f"""
2929
labelloc="t"
3030
labeljust="l"
31-
label=<<FONT POINT-SIZE="20">h11 state machine: {}</FONT>>
31+
label=<<FONT POINT-SIZE="20">h11 state machine: {machine_name}</FONT>>
3232
}}
33-
""".format(machine_name))
33+
""")
3434

3535
class Edges:
3636
def __init__(self):

h11/_connection.py

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,6 @@
11
# This contains the main Connection class. Everything in h11 revolves around
22
# this.
3-
from typing import (
4-
Any,
5-
Callable,
6-
cast,
7-
Dict,
8-
List,
9-
Optional,
10-
overload,
11-
Tuple,
12-
Type,
13-
Union,
14-
)
3+
from typing import Any, Callable, cast, Optional, overload, Union
154

165
from ._events import (
176
ConnectionClosed,
@@ -92,7 +81,7 @@ def _keep_alive(event: Union[Request, Response]) -> bool:
9281

9382
def _body_framing(
9483
request_method: bytes, event: Union[Request, Response]
95-
) -> Tuple[str, Union[Tuple[()], Tuple[int]]]:
84+
) -> tuple[str, Union[tuple[()], tuple[int]]]:
9685
# Called when we enter SEND_BODY to figure out framing information for
9786
# this body.
9887
#
@@ -166,15 +155,15 @@ class Connection:
166155

167156
def __init__(
168157
self,
169-
our_role: Type[Sentinel],
158+
our_role: type[Sentinel],
170159
max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE,
171160
) -> None:
172161
self._max_incomplete_event_size = max_incomplete_event_size
173162
# State and role tracking
174163
if our_role not in (CLIENT, SERVER):
175164
raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}")
176165
self.our_role = our_role
177-
self.their_role: Type[Sentinel]
166+
self.their_role: type[Sentinel]
178167
if our_role is CLIENT:
179168
self.their_role = SERVER
180169
else:
@@ -204,7 +193,7 @@ def __init__(
204193
self.client_is_waiting_for_100_continue = False
205194

206195
@property
207-
def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
196+
def states(self) -> dict[type[Sentinel], type[Sentinel]]:
208197
"""A dictionary like::
209198
210199
{CLIENT: <client state>, SERVER: <server state>}
@@ -215,14 +204,14 @@ def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
215204
return dict(self._cstate.states)
216205

217206
@property
218-
def our_state(self) -> Type[Sentinel]:
207+
def our_state(self) -> type[Sentinel]:
219208
"""The current state of whichever role we are playing. See
220209
:ref:`state-machine` for details.
221210
"""
222211
return self._cstate.states[self.our_role]
223212

224213
@property
225-
def their_state(self) -> Type[Sentinel]:
214+
def their_state(self) -> type[Sentinel]:
226215
"""The current state of whichever role we are NOT playing. See
227216
:ref:`state-machine` for details.
228217
"""
@@ -252,12 +241,12 @@ def start_next_cycle(self) -> None:
252241
assert not self.client_is_waiting_for_100_continue
253242
self._respond_to_state_changes(old_states)
254243

255-
def _process_error(self, role: Type[Sentinel]) -> None:
244+
def _process_error(self, role: type[Sentinel]) -> None:
256245
old_states = dict(self._cstate.states)
257246
self._cstate.process_error(role)
258247
self._respond_to_state_changes(old_states)
259248

260-
def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
249+
def _server_switch_event(self, event: Event) -> Optional[type[Sentinel]]:
261250
if type(event) is InformationalResponse and event.status_code == 101:
262251
return _SWITCH_UPGRADE
263252
if type(event) is Response:
@@ -269,7 +258,7 @@ def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
269258
return None
270259

271260
# All events go through here
272-
def _process_event(self, role: Type[Sentinel], event: Event) -> None:
261+
def _process_event(self, role: type[Sentinel], event: Event) -> None:
273262
# First, pass the event through the state machine to make sure it
274263
# succeeds.
275264
old_states = dict(self._cstate.states)
@@ -319,7 +308,7 @@ def _process_event(self, role: Type[Sentinel], event: Event) -> None:
319308

320309
def _get_io_object(
321310
self,
322-
role: Type[Sentinel],
311+
role: type[Sentinel],
323312
event: Optional[Event],
324313
io_dict: Union[ReadersType, WritersType],
325314
) -> Optional[Callable[..., Any]]:
@@ -341,7 +330,7 @@ def _get_io_object(
341330
# self._cstate.states to change.
342331
def _respond_to_state_changes(
343332
self,
344-
old_states: Dict[Type[Sentinel], Type[Sentinel]],
333+
old_states: dict[type[Sentinel], type[Sentinel]],
345334
event: Optional[Event] = None,
346335
) -> None:
347336
# Update reader/writer
@@ -351,7 +340,7 @@ def _respond_to_state_changes(
351340
self._reader = self._get_io_object(self.their_role, event, READERS)
352341

353342
@property
354-
def trailing_data(self) -> Tuple[bytes, bool]:
343+
def trailing_data(self) -> tuple[bytes, bool]:
355344
"""Data that has been received, but not yet processed, represented as
356345
a tuple with two elements, where the first is a byte-string containing
357346
the unprocessed data itself, and the second is a bool that is True if
@@ -409,7 +398,7 @@ def receive_data(self, data: bytes) -> None:
409398

410399
def _extract_next_receive_event(
411400
self,
412-
) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
401+
) -> Union[Event, type[NEED_DATA], type[PAUSED]]:
413402
state = self.their_state
414403
# We don't pause immediately when they enter DONE, because even in
415404
# DONE state we can still process a ConnectionClosed() event. But
@@ -435,7 +424,7 @@ def _extract_next_receive_event(
435424
event = NEED_DATA
436425
return event # type: ignore[no-any-return]
437426

438-
def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
427+
def next_event(self) -> Union[Event, type[NEED_DATA], type[PAUSED]]:
439428
"""Parse the next event out of our receive buffer, update our internal
440429
state, and return it.
441430
@@ -541,7 +530,7 @@ def send(self, event: Event) -> Optional[bytes]:
541530
else:
542531
return b"".join(data_list)
543532

544-
def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
533+
def send_with_data_passthrough(self, event: Event) -> Optional[list[bytes]]:
545534
"""Identical to :meth:`send`, except that in situations where
546535
:meth:`send` returns a single :term:`bytes-like object`, this instead
547536
returns a list of them -- and when sending a :class:`Data` event, this
@@ -567,7 +556,7 @@ def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
567556
# In any situation where writer is None, process_event should
568557
# have raised ProtocolError
569558
assert writer is not None
570-
data_list: List[bytes] = []
559+
data_list: list[bytes] = []
571560
writer(event, data_list.append)
572561
return data_list
573562
except:

h11/_events.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import re
99
from abc import ABC
1010
from dataclasses import dataclass
11-
from typing import List, Tuple, Union
11+
from typing import Union
1212

1313
from ._abnf import method, request_target
1414
from ._headers import Headers, normalize_and_validate
@@ -83,7 +83,7 @@ def __init__(
8383
self,
8484
*,
8585
method: Union[bytes, str],
86-
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
86+
headers: Union[Headers, list[tuple[bytes, bytes]], list[tuple[str, str]]],
8787
target: Union[bytes, str],
8888
http_version: Union[bytes, str] = b"1.1",
8989
_parsed: bool = False,
@@ -137,7 +137,7 @@ class _ResponseBase(Event):
137137
def __init__(
138138
self,
139139
*,
140-
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
140+
headers: Union[Headers, list[tuple[bytes, bytes]], list[tuple[str, str]]],
141141
status_code: int,
142142
http_version: Union[bytes, str] = b"1.1",
143143
reason: Union[bytes, str] = b"",
@@ -207,7 +207,7 @@ def __post_init__(self) -> None:
207207
if not (100 <= self.status_code < 200):
208208
raise LocalProtocolError(
209209
"InformationalResponse status_code should be in range "
210-
"[100, 200), not {}".format(self.status_code)
210+
f"[100, 200), not {self.status_code}"
211211
)
212212

213213
# This is an unhashable type.
@@ -247,9 +247,7 @@ class Response(_ResponseBase):
247247
def __post_init__(self) -> None:
248248
if not (200 <= self.status_code < 1000):
249249
raise LocalProtocolError(
250-
"Response status_code should be in range [200, 1000), not {}".format(
251-
self.status_code
252-
)
250+
f"Response status_code should be in range [200, 1000), not {self.status_code}"
253251
)
254252

255253
# This is an unhashable type.
@@ -338,7 +336,7 @@ def __init__(
338336
self,
339337
*,
340338
headers: Union[
341-
Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None
339+
Headers, list[tuple[bytes, bytes]], list[tuple[str, str]], None
342340
] = None,
343341
_parsed: bool = False,
344342
) -> None:

h11/_headers.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
2-
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
2+
from collections.abc import Sequence
3+
from typing import overload, TYPE_CHECKING, Union
34

45
from ._abnf import field_name, field_value
56
from ._util import bytesify, LocalProtocolError, validate
@@ -74,7 +75,7 @@
7475
_field_value_re = re.compile(field_value.encode("ascii"))
7576

7677

77-
class Headers(Sequence[Tuple[bytes, bytes]]):
78+
class Headers(Sequence[tuple[bytes, bytes]]):
7879
"""
7980
A list-like interface that allows iterating over headers as byte-pairs
8081
of (lowercased-name, value).
@@ -101,7 +102,7 @@ class Headers(Sequence[Tuple[bytes, bytes]]):
101102

102103
__slots__ = "_full_items"
103104

104-
def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None:
105+
def __init__(self, full_items: list[tuple[bytes, bytes, bytes]]) -> None:
105106
self._full_items = full_items
106107

107108
def __bool__(self) -> bool:
@@ -114,21 +115,21 @@ def __len__(self) -> int:
114115
return len(self._full_items)
115116

116117
def __repr__(self) -> str:
117-
return "<Headers(%s)>" % repr(list(self))
118+
return f"<Headers({repr(list(self))})>"
118119

119-
def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override]
120+
def __getitem__(self, idx: int) -> tuple[bytes, bytes]: # type: ignore[override]
120121
_, name, value = self._full_items[idx]
121122
return (name, value)
122123

123-
def raw_items(self) -> List[Tuple[bytes, bytes]]:
124+
def raw_items(self) -> list[tuple[bytes, bytes]]:
124125
return [(raw_name, value) for raw_name, _, value in self._full_items]
125126

126127

127128
HeaderTypes = Union[
128-
List[Tuple[bytes, bytes]],
129-
List[Tuple[bytes, str]],
130-
List[Tuple[str, bytes]],
131-
List[Tuple[str, str]],
129+
list[tuple[bytes, bytes]],
130+
list[tuple[bytes, str]],
131+
list[tuple[str, bytes]],
132+
list[tuple[str, str]],
132133
]
133134

134135

@@ -206,7 +207,7 @@ def normalize_and_validate(
206207
return Headers(new_headers)
207208

208209

209-
def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
210+
def get_comma_header(headers: Headers, name: bytes) -> list[bytes]:
210211
# Should only be used for headers whose value is a list of
211212
# comma-separated, case-insensitive values.
212213
#
@@ -242,7 +243,7 @@ def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
242243
# Expect: the only legal value is the literal string
243244
# "100-continue". Splitting on commas is harmless. Case insensitive.
244245
#
245-
out: List[bytes] = []
246+
out: list[bytes] = []
246247
for _, found_name, found_raw_value in headers._full_items:
247248
if found_name == name:
248249
found_raw_value = found_raw_value.lower()
@@ -253,7 +254,7 @@ def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
253254
return out
254255

255256

256-
def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
257+
def set_comma_header(headers: Headers, name: bytes, new_values: list[bytes]) -> Headers:
257258
# The header name `name` is expected to be lower-case bytes.
258259
#
259260
# Note that when we store the header we use title casing for the header
@@ -263,7 +264,7 @@ def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) ->
263264
# here given the cases where we're using `set_comma_header`...
264265
#
265266
# Connection, Content-Length, Transfer-Encoding.
266-
new_headers: List[Tuple[bytes, bytes]] = []
267+
new_headers: list[tuple[bytes, bytes]] = []
267268
for found_raw_name, found_name, found_raw_value in headers._full_items:
268269
if found_name != name:
269270
new_headers.append((found_raw_name, found_raw_value))

h11/_readers.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
# - or, for body readers, a dict of per-framing reader factories
1818

1919
import re
20-
from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union
20+
from collections.abc import Iterable
21+
from typing import Any, Callable, NoReturn, Optional, Union
2122

2223
from ._abnf import chunk_header, header_field, request_line, status_line
2324
from ._events import Data, EndOfMessage, InformationalResponse, Request, Response
@@ -63,7 +64,7 @@ def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]:
6364

6465
def _decode_header_lines(
6566
lines: Iterable[bytes],
66-
) -> Iterable[Tuple[bytes, bytes]]:
67+
) -> Iterable[tuple[bytes, bytes]]:
6768
for line in _obsolete_line_fold(lines):
6869
matches = validate(header_field_re, line, "illegal header line: {!r}", line)
6970
yield (matches["field_name"], matches["field_value"])
@@ -107,7 +108,7 @@ def maybe_read_from_SEND_RESPONSE_server(
107108
)
108109
reason = b"" if matches["reason"] is None else matches["reason"]
109110
status_code = int(matches["status_code"])
110-
class_: Union[Type[InformationalResponse], Type[Response]] = (
111+
class_: Union[type[InformationalResponse], type[Response]] = (
111112
InformationalResponse if status_code < 200 else Response
112113
)
113114
return class_(
@@ -136,9 +137,7 @@ def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:
136137
def read_eof(self) -> NoReturn:
137138
raise RemoteProtocolError(
138139
"peer closed connection without sending complete message body "
139-
"(received {} bytes, expected {})".format(
140-
self._length - self._remaining, self._length
141-
)
140+
f"(received {self._length - self._remaining} bytes, expected {self._length})"
142141
)
143142

144143

@@ -227,9 +226,9 @@ def expect_nothing(buf: ReceiveBuffer) -> None:
227226
return None
228227

229228

230-
ReadersType = Dict[
231-
Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]],
232-
Union[Callable[..., Any], Dict[str, Callable[..., Any]]],
229+
ReadersType = dict[
230+
Union[type[Sentinel], tuple[type[Sentinel], type[Sentinel]]],
231+
Union[Callable[..., Any], dict[str, Callable[..., Any]]],
233232
]
234233

235234
READERS: ReadersType = {

h11/_receivebuffer.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import re
2-
import sys
3-
from typing import List, Optional, Union
2+
from typing import Optional, Union
43

54
__all__ = ["ReceiveBuffer"]
65

@@ -101,7 +100,7 @@ def maybe_extract_next_line(self) -> Optional[bytearray]:
101100

102101
return self._extract(idx)
103102

104-
def maybe_extract_lines(self) -> Optional[List[bytearray]]:
103+
def maybe_extract_lines(self) -> Optional[list[bytearray]]:
105104
"""
106105
Extract everything up to the first blank line, and return a list of lines.
107106
"""

0 commit comments

Comments
 (0)