Skip to content

Commit d6d9a0f

Browse files
committed
ruff auto-fixes
1 parent 51179b4 commit d6d9a0f

20 files changed

+418
-321
lines changed

bench/connection.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import random
24
import time
35
from typing import List

docs/source/conf.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,28 @@
1010
# add these directories to sys.path here. If the directory is relative to the
1111
# documentation root, use os.path.abspath to make it absolute, like shown here.
1212
#
13+
from __future__ import annotations
14+
1315
import os
14-
import sys
1516
import re
17+
import sys
1618

17-
sys.path.insert(0, os.path.abspath('../..'))
19+
sys.path.insert(0, os.path.abspath("../.."))
1820

1921
PROJECT_ROOT = os.path.dirname(__file__)
2022
# Get the version
2123
version_regex = r'__version__ = ["\']([^"\']*)["\']'
22-
with open(os.path.join(PROJECT_ROOT, '../../', 'src/wsproto/__init__.py')) as file_:
24+
with open(os.path.join(PROJECT_ROOT, "../../", "src/wsproto/__init__.py")) as file_:
2325
text = file_.read()
2426
match = re.search(version_regex, text)
2527
version = match.group(1)
2628

2729

2830
# -- Project information -----------------------------------------------------
2931

30-
project = 'wsproto'
31-
copyright = '2020, Benno Rice'
32-
author = 'Benno Rice'
32+
project = "wsproto"
33+
copyright = "2020, Benno Rice"
34+
author = "Benno Rice"
3335
release = version
3436

3537
# -- General configuration ---------------------------------------------------
@@ -38,13 +40,13 @@
3840
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
3941
# ones.
4042
extensions = [
41-
'sphinx.ext.autodoc',
42-
'sphinx.ext.intersphinx',
43-
'sphinx.ext.viewcode',
43+
"sphinx.ext.autodoc",
44+
"sphinx.ext.intersphinx",
45+
"sphinx.ext.viewcode",
4446
]
4547

4648
# Add any paths that contain templates here, relative to this directory.
47-
templates_path = ['_templates']
49+
templates_path = ["_templates"]
4850

4951
# List of patterns, relative to source directory, that match files and
5052
# directories to ignore when looking for source files.
@@ -53,20 +55,20 @@
5355

5456
# Example configuration for intersphinx: refer to the Python standard library.
5557
intersphinx_mapping = {
56-
'python': ('https://docs.python.org/', None),
58+
"python": ("https://docs.python.org/", None),
5759
}
5860

59-
master_doc = 'index'
61+
master_doc = "index"
6062

6163

6264
# -- Options for HTML output -------------------------------------------------
6365

6466
# The theme to use for HTML and HTML Help pages. See the documentation for
6567
# a list of builtin themes.
6668
#
67-
html_theme = 'default'
69+
html_theme = "default"
6870

6971
# Add any paths that contain custom static files (such as style sheets) here,
7072
# relative to this directory. They are copied after the builtin static files,
7173
# so a file named "default.css" will overwrite the builtin "default.css".
72-
html_static_path = ['_static']
74+
html_static_path = ["_static"]

example/synchronous_client.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
response. This is a poor implementation of a client. It is only intended to
44
demonstrate how to use wsproto.
55
"""
6+
from __future__ import annotations
67

78
import socket
89
import sys
@@ -28,7 +29,7 @@ def main() -> None:
2829
host = sys.argv[1]
2930
port = int(sys.argv[2])
3031
except (IndexError, ValueError):
31-
print("Usage: {} <HOST> <PORT>".format(sys.argv[0]))
32+
print(f"Usage: {sys.argv[0]} <HOST> <PORT>")
3233
sys.exit(1)
3334

3435
try:
@@ -47,7 +48,6 @@ def wsproto_demo(host: str, port: int) -> None:
4748
3) Send ping and display pong
4849
4) Negotiate WebSocket closing handshake
4950
"""
50-
5151
# 0) Open TCP connection
5252
print(f"Connecting to {host}:{port}")
5353
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -89,7 +89,7 @@ def wsproto_demo(host: str, port: int) -> None:
8989

9090
def net_send(out_data: bytes, conn: socket.socket) -> None:
9191
"""Write pending data from websocket to network."""
92-
print("Sending {} bytes".format(len(out_data)))
92+
print(f"Sending {len(out_data)} bytes")
9393
conn.send(out_data)
9494

9595

@@ -102,7 +102,7 @@ def net_recv(ws: WSConnection, conn: socket.socket) -> None:
102102
print("Received 0 bytes (connection closed)")
103103
ws.receive_data(None)
104104
else:
105-
print("Received {} bytes".format(len(in_data)))
105+
print(f"Received {len(in_data)} bytes")
106106
ws.receive_data(in_data)
107107

108108

example/synchronous_server.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
implementation of a server! It is only intended to demonstrate how to use
55
wsproto.
66
"""
7+
from __future__ import annotations
78

89
import socket
910
import sys
@@ -28,7 +29,7 @@ def main() -> None:
2829
ip = sys.argv[1]
2930
port = int(sys.argv[2])
3031
except (IndexError, ValueError):
31-
print("Usage: {} <BIND_IP> <PORT>".format(sys.argv[0]))
32+
print(f"Usage: {sys.argv[0]} <BIND_IP> <PORT>")
3233
sys.exit(1)
3334

3435
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -40,7 +41,7 @@ def main() -> None:
4041
while True:
4142
print("Waiting for connection...")
4243
(stream, addr) = server.accept()
43-
print("Client connected: {}:{}".format(addr[0], addr[1]))
44+
print(f"Client connected: {addr[0]}:{addr[1]}")
4445
handle_connection(stream)
4546
stream.shutdown(socket.SHUT_WR)
4647
stream.close()
@@ -67,7 +68,7 @@ def handle_connection(stream: socket.socket) -> None:
6768
while running:
6869
# 1) Read data from network
6970
in_data = stream.recv(RECEIVE_BYTES)
70-
print("Received {} bytes".format(len(in_data)))
71+
print(f"Received {len(in_data)} bytes")
7172
ws.receive_data(in_data)
7273

7374
# 2) Get new events and handle them
@@ -80,9 +81,7 @@ def handle_connection(stream: socket.socket) -> None:
8081
elif isinstance(event, CloseConnection):
8182
# Print log message and break out
8283
print(
83-
"Connection closed: code={} reason={}".format(
84-
event.code, event.reason
85-
)
84+
f"Connection closed: code={event.code} reason={event.reason}",
8685
)
8786
out_data += ws.send(event.response())
8887
running = False
@@ -100,7 +99,7 @@ def handle_connection(stream: socket.socket) -> None:
10099
print(f"Unknown event: {event!r}")
101100

102101
# 4) Send data from wsproto to network
103-
print("Sending {} bytes".format(len(out_data)))
102+
print(f"Sending {len(out_data)} bytes")
104103
stream.send(out_data)
105104

106105

src/wsproto/__init__.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,18 @@
44
55
A WebSocket implementation.
66
"""
7+
from __future__ import annotations
78

8-
from typing import Generator, Optional, Union
9+
from typing import TYPE_CHECKING, Optional, Union
910

1011
from .connection import Connection, ConnectionState, ConnectionType
11-
from .events import Event
1212
from .handshake import H11Handshake
13-
from .typing import Headers
13+
14+
if TYPE_CHECKING:
15+
from collections.abc import Generator
16+
17+
from .events import Event
18+
from .typing import Headers
1419

1520
__version__ = "1.2.0+dev"
1621

@@ -29,7 +34,7 @@ def __init__(self, connection_type: ConnectionType) -> None:
2934
"""
3035
self.client = connection_type is ConnectionType.CLIENT
3136
self.handshake = H11Handshake(connection_type)
32-
self.connection: Optional[Connection] = None
37+
self.connection: Connection | None = None
3338

3439
@property
3540
def state(self) -> ConnectionState:
@@ -42,7 +47,7 @@ def state(self) -> ConnectionState:
4247
return self.connection.state
4348

4449
def initiate_upgrade_connection(
45-
self, headers: Headers, path: Union[bytes, str]
50+
self, headers: Headers, path: bytes | str,
4651
) -> None:
4752
self.handshake.initiate_upgrade_connection(headers, path)
4853

@@ -65,7 +70,7 @@ def send(self, event: Event) -> bytes:
6570
data += self.connection.send(event)
6671
return data
6772

68-
def receive_data(self, data: Optional[bytes]) -> None:
73+
def receive_data(self, data: bytes | None) -> None:
6974
"""
7075
Feed network data into the connection instance.
7176

src/wsproto/connection.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
55
An implementation of a WebSocket connection.
66
"""
7+
from __future__ import annotations
78

89
from collections import deque
910
from enum import Enum
10-
from typing import Deque, Generator, List, Optional
11+
from typing import TYPE_CHECKING
1112

1213
from .events import (
1314
BytesMessage,
@@ -18,10 +19,14 @@
1819
Pong,
1920
TextMessage,
2021
)
21-
from .extensions import Extension
2222
from .frame_protocol import CloseReason, FrameProtocol, Opcode, ParseFailed
2323
from .utilities import LocalProtocolError
2424

25+
if TYPE_CHECKING:
26+
from collections.abc import Generator
27+
28+
from .extensions import Extension
29+
2530

2631
class ConnectionState(Enum):
2732
"""
@@ -68,7 +73,7 @@ class Connection:
6873
def __init__(
6974
self,
7075
connection_type: ConnectionType,
71-
extensions: Optional[List[Extension]] = None,
76+
extensions: list[Extension] | None = None,
7277
trailing_data: bytes = b"",
7378
) -> None:
7479
"""
@@ -82,7 +87,7 @@ def __init__(
8287
processed.
8388
"""
8489
self.client = connection_type is ConnectionType.CLIENT
85-
self._events: Deque[Event] = deque()
90+
self._events: deque[Event] = deque()
8691
self._proto = FrameProtocol(self.client, extensions or [])
8792
self._state = ConnectionState.OPEN
8893
self.receive_data(trailing_data)
@@ -109,12 +114,13 @@ def send(self, event: Event) -> bytes:
109114
else:
110115
self._state = ConnectionState.LOCAL_CLOSING
111116
else:
117+
msg = f"Event {event} cannot be sent in state {self.state}."
112118
raise LocalProtocolError(
113-
f"Event {event} cannot be sent in state {self.state}."
119+
msg,
114120
)
115121
return data
116122

117-
def receive_data(self, data: Optional[bytes]) -> None:
123+
def receive_data(self, data: bytes | None) -> None:
118124
"""
119125
Pass some received data to the connection for handling.
120126
@@ -124,7 +130,6 @@ def receive_data(self, data: Optional[bytes]) -> None:
124130
:param data: The data received from the remote peer on the network.
125131
:type data: ``bytes``
126132
"""
127-
128133
if data is None:
129134
# "If _The WebSocket Connection is Closed_ and no Close control
130135
# frame was received by the endpoint (such as could occur if the
@@ -137,7 +142,8 @@ def receive_data(self, data: Optional[bytes]) -> None:
137142
if self.state in (ConnectionState.OPEN, ConnectionState.LOCAL_CLOSING):
138143
self._proto.receive_bytes(data)
139144
elif self.state is ConnectionState.CLOSED:
140-
raise LocalProtocolError("Connection already closed.")
145+
msg = "Connection already closed."
146+
raise LocalProtocolError(msg)
141147
else:
142148
pass # pragma: no cover
143149

@@ -154,12 +160,14 @@ def events(self) -> Generator[Event, None, None]:
154160
try:
155161
for frame in self._proto.received_frames():
156162
if frame.opcode is Opcode.PING:
157-
assert frame.frame_finished and frame.message_finished
163+
assert frame.frame_finished
164+
assert frame.message_finished
158165
assert isinstance(frame.payload, (bytes, bytearray))
159166
yield Ping(payload=frame.payload)
160167

161168
elif frame.opcode is Opcode.PONG:
162-
assert frame.frame_finished and frame.message_finished
169+
assert frame.frame_finished
170+
assert frame.message_finished
163171
assert isinstance(frame.payload, (bytes, bytearray))
164172
yield Pong(payload=frame.payload)
165173

0 commit comments

Comments
 (0)