Skip to content

Commit 59c3f64

Browse files
committed
f-strings, code cleanup (unitialized and shadowed vars)
1 parent 3b6f4e7 commit 59c3f64

File tree

5 files changed

+44
-52
lines changed

5 files changed

+44
-52
lines changed

autobahn/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ async def get_case_count(url):
2424

2525

2626
async def run_case(url, case):
27-
url = url + '/runCase?case={}&agent={}'.format(case, AGENT)
27+
url = f'{url}/runCase?case={case}&agent={AGENT}'
2828
try:
2929
async with open_websocket_url(url, max_message_size=MAX_MESSAGE_SIZE) as conn:
3030
while True:
@@ -35,7 +35,7 @@ async def run_case(url, case):
3535

3636

3737
async def update_reports(url):
38-
url = url + '/updateReports?agent={}'.format(AGENT)
38+
url = f'{url}/updateReports?agent={AGENT}'
3939
async with open_websocket_url(url) as conn:
4040
# This command runs as soon as we connect to it, so we don't need to
4141
# send any messages.

examples/client.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,8 @@ async def handle_connection(ws, use_heartbeat):
7171
nursery.start_soon(get_commands, ws)
7272
nursery.start_soon(get_messages, ws)
7373
except ConnectionClosed as cc:
74-
reason = '<no reason>' if cc.reason.reason is None else '"{}"'.format(
75-
cc.reason.reason)
76-
print('Closed: {}/{} {}'.format(cc.reason.code, cc.reason.name, reason))
74+
reason = '<no reason>' if cc.reason.reason is None else f'"{cc.reason.reason}"'
75+
print(f'Closed: {cc.reason.code}/{cc.reason.name} {reason}')
7776

7877

7978
async def heartbeat(ws, timeout, interval):
@@ -128,7 +127,7 @@ async def get_messages(ws):
128127
''' In a loop: get a WebSocket message and print it out. '''
129128
while True:
130129
message = await ws.get_message()
131-
print('message: {}'.format(message))
130+
print(f'message: {message}')
132131

133132

134133
if __name__ == '__main__':

examples/generate-cert.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ def main():
1313
print('Creating self-signed certificate for localhost/127.0.0.1:')
1414
ca_cert = trustme.CA()
1515
ca_cert.cert_pem.write_to_path(ca_path)
16-
print (' * CA certificate: {}'.format(ca_path))
16+
print(f' * CA certificate: {ca_path}')
1717
server_cert = ca_cert.issue_server_cert('localhost', '127.0.0.1')
1818
server_cert.private_key_and_cert_chain_pem.write_to_path(server_path)
19-
print (' * Server certificate: {}'.format(server_path))
19+
print(f' * Server certificate: {server_path}')
2020
print('Done')
2121

2222

tests/test_connection.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,7 @@ async def wrapper(*args, **kwargs):
119119
with trio.move_on_after(self._seconds) as cancel_scope:
120120
await fn(*args, **kwargs)
121121
if cancel_scope.cancelled_caught:
122-
pytest.fail('Test runtime exceeded the maximum {} seconds'
123-
.format(self._seconds))
122+
pytest.fail(f'Test runtime exceeded the maximum {self._seconds} seconds')
124123
return wrapper
125124

126125

@@ -281,7 +280,7 @@ async def test_client_open(echo_server):
281280
(RESOURCE + '?foo=bar', RESOURCE + '?foo=bar')
282281
])
283282
async def test_client_open_url(path, expected_path, echo_server):
284-
url = 'ws://{}:{}{}'.format(HOST, echo_server.port, path)
283+
url = f'ws://{HOST}:{echo_server.port}{path}'
285284
async with open_websocket_url(url) as conn:
286285
assert conn.path == expected_path
287286

@@ -294,7 +293,7 @@ async def test_client_open_invalid_url(echo_server):
294293

295294
async def test_ascii_encoded_path_is_ok(echo_server):
296295
path = '%D7%90%D7%91%D7%90?%D7%90%D7%9E%D7%90'
297-
url = 'ws://{}:{}{}/{}'.format(HOST, echo_server.port, RESOURCE, path)
296+
url = f'ws://{HOST}:{echo_server.port}{RESOURCE}/{path}'
298297
async with open_websocket_url(url) as conn:
299298
assert conn.path == RESOURCE + '/' + path
300299

@@ -303,7 +302,7 @@ async def test_ascii_encoded_path_is_ok(echo_server):
303302
def test_client_open_url_options(open_websocket_mock):
304303
"""open_websocket_url() must pass its options on to open_websocket()"""
305304
port = 1234
306-
url = 'ws://{}:{}{}'.format(HOST, port, RESOURCE)
305+
url = f'ws://{HOST}:{port}{RESOURCE}'
307306
options = {
308307
'subprotocols': ['chat'],
309308
'extra_headers': [(b'X-Test-Header', b'My test header')],
@@ -330,7 +329,7 @@ async def test_client_connect(echo_server, nursery):
330329

331330

332331
async def test_client_connect_url(echo_server, nursery):
333-
url = 'ws://{}:{}{}'.format(HOST, echo_server.port, RESOURCE)
332+
url = f'ws://{HOST}:{echo_server.port}{RESOURCE}'
334333
conn = await connect_websocket_url(nursery, url)
335334
assert not conn.closed
336335

trio_websocket/_impl.py

Lines changed: 32 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import ssl
99
import struct
1010
import urllib.parse
11+
from typing import List
1112

1213
from async_generator import asynccontextmanager
1314
import trio
@@ -174,9 +175,10 @@ async def connect_websocket(nursery, host, port, resource, *, use_ssl,
174175
if port in (80, 443):
175176
host_header = host
176177
else:
177-
host_header = '{}:{}'.format(host, port)
178-
wsproto = WSConnection(ConnectionType.CLIENT)
179-
connection = WebSocketConnection(stream, wsproto, host=host_header,
178+
host_header = f'{host}:{port}'
179+
connection = WebSocketConnection(stream,
180+
WSConnection(ConnectionType.CLIENT),
181+
host=host_header,
180182
path=resource,
181183
client_subprotocols=subprotocols, client_extra_headers=extra_headers,
182184
message_queue_size=message_queue_size,
@@ -328,8 +330,9 @@ async def wrap_client_stream(nursery, stream, host, resource, *,
328330
then the connection is closed with code 1009 (Message Too Big).
329331
:rtype: WebSocketConnection
330332
'''
331-
wsproto = WSConnection(ConnectionType.CLIENT)
332-
connection = WebSocketConnection(stream, wsproto, host=host, path=resource,
333+
connection = WebSocketConnection(stream,
334+
WSConnection(ConnectionType.CLIENT),
335+
host=host, path=resource,
333336
client_subprotocols=subprotocols, client_extra_headers=extra_headers,
334337
message_queue_size=message_queue_size,
335338
max_message_size=max_message_size)
@@ -356,8 +359,8 @@ async def wrap_server_stream(nursery, stream,
356359
:type stream: trio.abc.Stream
357360
:rtype: WebSocketRequest
358361
'''
359-
wsproto = WSConnection(ConnectionType.SERVER)
360-
connection = WebSocketConnection(stream, wsproto,
362+
connection = WebSocketConnection(stream,
363+
WSConnection(ConnectionType.SERVER),
361364
message_queue_size=message_queue_size,
362365
max_message_size=max_message_size)
363366
nursery.start_soon(connection._reader_task)
@@ -446,7 +449,7 @@ def __init__(self, reason):
446449

447450
def __repr__(self):
448451
''' Return representation. '''
449-
return '{}<{}>'.format(self.__class__.__name__, self.reason)
452+
return f'{self.__class__.__name__}<{self.reason}>'
450453

451454

452455
class ConnectionRejected(HandshakeError):
@@ -471,8 +474,7 @@ def __init__(self, status_code, headers, body):
471474

472475
def __repr__(self):
473476
''' Return representation. '''
474-
return '{}<status_code={}>'.format(self.__class__.__name__,
475-
self.status_code)
477+
return f'{self.__class__.__name__}<status_code={self.status_code}>'
476478

477479

478480
class CloseReason:
@@ -515,8 +517,8 @@ def reason(self):
515517

516518
def __repr__(self):
517519
''' Show close code, name, and reason. '''
518-
return '{}<code={}, name={}, reason={}>'.format(self.__class__.__name__,
519-
self.code, self.name, self.reason)
520+
return f'{self.__class__.__name__}' \
521+
f'<code={self.code}, name={self.name}, reason={self.reason}>'
520522

521523

522524
class Future:
@@ -619,7 +621,7 @@ async def accept(self, *, subprotocol=None, extra_headers=None):
619621
:rtype: WebSocketConnection
620622
'''
621623
if extra_headers is None:
622-
extra_headers = list()
624+
extra_headers = []
623625
await self._connection._accept(self._event, subprotocol, extra_headers)
624626
return self._connection
625627

@@ -651,14 +653,12 @@ def _get_stream_endpoint(stream, *, local):
651653
represented as an endpoint.
652654
:rtype: Endpoint or str
653655
'''
656+
socket, is_ssl = None, False
654657
if isinstance(stream, trio.SocketStream):
655658
socket = stream.socket
656-
is_ssl = False
657659
elif isinstance(stream, trio.SSLStream):
658660
socket = stream.transport_stream.socket
659661
is_ssl = True
660-
else:
661-
socket = None
662662
if socket:
663663
addr, port, *_ = socket.getsockname() if local else socket.getpeername()
664664
endpoint = Endpoint(addr, port, is_ssl)
@@ -672,7 +672,7 @@ class WebSocketConnection(trio.abc.AsyncResource):
672672

673673
CONNECTION_ID = itertools.count()
674674

675-
def __init__(self, stream, wsproto, *, host=None, path=None,
675+
def __init__(self, stream, ws_connection, *, host=None, path=None,
676676
client_subprotocols=None, client_extra_headers=None,
677677
message_queue_size=MESSAGE_QUEUE_SIZE,
678678
max_message_size=MAX_MESSAGE_SIZE):
@@ -688,7 +688,7 @@ def __init__(self, stream, wsproto, *, host=None, path=None,
688688
for you.
689689
690690
:param SocketStream stream:
691-
:type wsproto: wsproto.WSConnection
691+
:param ws_connection wsproto.WSConnection:
692692
:param str host: The hostname to send in the HTTP request headers. Only
693693
used for client connections.
694694
:param str path: The URL path for this connection.
@@ -706,12 +706,12 @@ def __init__(self, stream, wsproto, *, host=None, path=None,
706706
self._id = next(self.__class__.CONNECTION_ID)
707707
self._stream = stream
708708
self._stream_lock = trio.StrictFIFOLock()
709-
self._wsproto = wsproto
709+
self._wsproto = ws_connection
710710
self._message_size = 0
711711
self._message_parts = [] # type: List[bytes|str]
712712
self._max_message_size = max_message_size
713713
self._reader_running = True
714-
if wsproto.client:
714+
if ws_connection.client:
715715
self._initial_request = Request(host=host, target=path,
716716
subprotocols=client_subprotocols,
717717
extra_headers=client_extra_headers or [])
@@ -895,8 +895,7 @@ async def ping(self, payload=None):
895895
if self._close_reason:
896896
raise ConnectionClosed(self._close_reason)
897897
if payload in self._pings:
898-
raise ValueError('Payload value {} is already in flight.'.
899-
format(payload))
898+
raise ValueError(f'Payload value {payload} is already in flight.')
900899
if payload is None:
901900
payload = struct.pack('!I', random.getrandbits(32))
902901
event = trio.Event()
@@ -938,7 +937,7 @@ async def send_message(self, message):
938937
def __str__(self):
939938
''' Connection ID and type. '''
940939
type_ = 'client' if self.is_client else 'server'
941-
return '{}-{}'.format(type_, self._id)
940+
return f'{type_}-{self._id}'
942941

943942
async def _accept(self, request, subprotocol, extra_headers):
944943
'''
@@ -1110,8 +1109,7 @@ async def _handle_message_event(self, event):
11101109
self._message_size += len(event.data)
11111110
self._message_parts.append(event.data)
11121111
if self._message_size > self._max_message_size:
1113-
err = 'Exceeded maximum message size: {} bytes'.format(
1114-
self._max_message_size)
1112+
err = f'Exceeded maximum message size: {self._max_message_size} bytes'
11151113
self._message_size = 0
11161114
self._message_parts = []
11171115
self._close_reason = CloseReason(1009, err)
@@ -1276,13 +1274,12 @@ def url(self):
12761274
else:
12771275
port_str = ':' + str(self.port)
12781276
if self.address.version == 4:
1279-
return '{}://{}{}'.format(scheme, self.address, port_str)
1280-
return '{}://[{}]{}'.format(scheme, self.address, port_str)
1277+
return f'{scheme}://{self.address}{port_str}'
1278+
return f'{scheme}://[{self.address}]{port_str}'
12811279

12821280
def __repr__(self):
12831281
''' Return endpoint info as string. '''
1284-
return 'Endpoint(address="{}", port={}, is_ssl={})'.format(self.address,
1285-
self.port, self.is_ssl)
1282+
return f'Endpoint(address="{self.address}", port={self.port}, is_ssl={self.is_ssl})'
12861283

12871284

12881285
class WebSocketServer:
@@ -1343,12 +1340,11 @@ def port(self):
13431340
if len(self._listeners) > 1:
13441341
raise RuntimeError('Cannot get port because this server has'
13451342
' more than 1 listeners.')
1343+
listener = self.listeners[0]
13461344
try:
1347-
listener = self.listeners[0]
13481345
return listener.port
13491346
except AttributeError:
1350-
raise RuntimeError('This socket does not have a port: {!r}'
1351-
.format(listener)) from None
1347+
raise RuntimeError(f'This socket does not have a port: {repr(listener)}') from None
13521348

13531349
@property
13541350
def listeners(self):
@@ -1360,16 +1356,14 @@ def listeners(self):
13601356
:returns: Listeners
13611357
:rtype list[Endpoint or str]:
13621358
'''
1363-
listeners = list()
1359+
listeners = []
13641360
for listener in self._listeners:
1361+
socket, is_ssl = None, False
13651362
if isinstance(listener, trio.SocketListener):
13661363
socket = listener.socket
1367-
is_ssl = False
13681364
elif isinstance(listener, trio.SSLListener):
13691365
socket = listener.transport_listener.socket
13701366
is_ssl = True
1371-
else:
1372-
socket = None
13731367
if socket:
13741368
sockname = socket.getsockname()
13751369
listeners.append(Endpoint(sockname[0], sockname[1], is_ssl))
@@ -1407,8 +1401,8 @@ async def _handle_connection(self, stream):
14071401
:type stream: trio.abc.Stream
14081402
'''
14091403
async with trio.open_nursery() as nursery:
1410-
wsproto = WSConnection(ConnectionType.SERVER)
1411-
connection = WebSocketConnection(stream, wsproto,
1404+
connection = WebSocketConnection(stream,
1405+
WSConnection(ConnectionType.SERVER),
14121406
message_queue_size=self._message_queue_size,
14131407
max_message_size=self._max_message_size)
14141408
nursery.start_soon(connection._reader_task)

0 commit comments

Comments
 (0)