Skip to content

Commit cee77a0

Browse files
committed
Chore: Conform src/autobahn to ruff's UP rules
1 parent b006e90 commit cee77a0

Some content is hidden

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

57 files changed

+1027
-1834
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
- [x] I did **not** use any AI-assistance tools to help create this pull request.
2+
- [ ] I **did** use AI-assistance tools to *help* create this pull request.
3+
- [x] I have read, understood and followed the projects' [AI Policy](https://github.com/crossbario/autobahn-python/blob/main/AI_POLICY.md) when creating code, documentation etc. for this pull request.
4+
5+
Submitted by: @bblommers
6+
Date: 2026-01-09
7+
Related issue(s): #1841
8+
Branch: bblommers:chore-apply-ruff-up

src/autobahn/__main__.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ def do_call(reactor, session, options):
231231
call_kwargs = {k: v for k, v in options.keyword}
232232

233233
results = yield session.call(options.uri, *call_args, **call_kwargs)
234-
print("result: {}".format(results))
234+
print(f"result: {results}")
235235

236236

237237
@inlineCallbacks
@@ -260,11 +260,11 @@ def do_register(reactor, session, options):
260260

261261
@inlineCallbacks
262262
def called(*args, **kw):
263-
print("called: args={}, kwargs={}".format(args, kw), file=sys.stderr)
263+
print(f"called: args={args}, kwargs={kw}", file=sys.stderr)
264264
env = copy(os.environ)
265265
env["WAMP_ARGS"] = " ".join(args)
266266
env["WAMP_ARGS_JSON"] = json.dumps(args)
267-
env["WAMP_KWARGS"] = " ".join("{}={}".format(k, v) for k, v in kw.items())
267+
env["WAMP_KWARGS"] = " ".join(f"{k}={v}" for k, v in kw.items())
268268
env["WAMP_KWARGS_JSON"] = json.dumps(kw)
269269

270270
exe = os.path.abspath(options.command[0])
@@ -286,7 +286,7 @@ def processExited(self, reason):
286286
code = yield done
287287

288288
if code != 0:
289-
print("Failed with exit-code {}".format(code))
289+
print(f"Failed with exit-code {code}")
290290
if countdown[0]:
291291
countdown[0] -= 1
292292
if countdown[0] <= 0:
@@ -350,12 +350,12 @@ def _real_main(reactor):
350350
exe = options.command[0]
351351
if not os.path.isabs(exe):
352352
print(
353-
"Full path to the executable required. Found: {}".format(exe),
353+
f"Full path to the executable required. Found: {exe}",
354354
file=sys.stderr,
355355
)
356356
sys.exit(1)
357357
if not os.path.exists(exe):
358-
print("Executable not found: {}".format(exe), file=sys.stderr)
358+
print(f"Executable not found: {exe}", file=sys.stderr)
359359
sys.exit(1)
360360

361361
subcommands = {
@@ -372,9 +372,7 @@ def _real_main(reactor):
372372
@inlineCallbacks
373373
def _(session, details):
374374
print(
375-
"connected: authrole={} authmethod={}".format(
376-
details.authrole, details.authmethod
377-
),
375+
f"connected: authrole={details.authrole} authmethod={details.authmethod}",
378376
file=sys.stderr,
379377
)
380378
try:
@@ -388,10 +386,10 @@ def _(session, details):
388386

389387
@component.on_connectfailure
390388
def _(comp, fail):
391-
print("connect failure: {}".format(fail))
389+
print(f"connect failure: {fail}")
392390
failures.append(fail)
393391
if options.max_failures > 0 and len(failures) > options.max_failures:
394-
print("Too many failures ({}). Exiting".format(len(failures)))
392+
print(f"Too many failures ({len(failures)}). Exiting")
395393
reactor.stop()
396394

397395
yield component.start(reactor)

src/autobahn/_flatc/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@
5353
import subprocess
5454
import sys
5555
from pathlib import Path
56-
from typing import List, Optional
5756

5857

5958
def get_flatc_path() -> Path:
@@ -79,7 +78,7 @@ def get_flatc_path() -> Path:
7978
return flatc_path
8079

8180

82-
def run_flatc(args: List[str], cwd: Optional[str] = None) -> int:
81+
def run_flatc(args: list[str], cwd: str | None = None) -> int:
8382
"""
8483
Run the bundled flatc with the given arguments.
8584

src/autobahn/asyncio/__init__.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -52,18 +52,9 @@
5252
if USES_NVX:
5353
import cffi
5454

55-
__ident__ = "Autobahn/{}-NVXCFFI/{}-asyncio-{}/{}".format(
56-
autobahn.__version__,
57-
cffi.__version__,
58-
platform.python_implementation(),
59-
platform.python_version(),
60-
)
55+
__ident__ = f"Autobahn/{autobahn.__version__}-NVXCFFI/{cffi.__version__}-asyncio-{platform.python_implementation()}/{platform.python_version()}"
6156
else:
62-
__ident__ = "Autobahn/{}-asyncio-{}/{}".format(
63-
autobahn.__version__,
64-
platform.python_implementation(),
65-
platform.python_version(),
66-
)
57+
__ident__ = f"Autobahn/{autobahn.__version__}-asyncio-{platform.python_implementation()}/{platform.python_version()}"
6758

6859
"""
6960
Identification string for the Autobahn|Python asyncio backend.

src/autobahn/asyncio/component.py

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def _create_transport_factory(loop, transport, session_factory):
8989
factory.setProtocolOptions(**{_camel_case_from_snake_case(k): v})
9090
except (TypeError, KeyError):
9191
raise ValueError(
92-
"Unknown {} transport option: {}={}".format(transport.type, k, v)
92+
f"Unknown {transport.type} transport option: {k}={v}"
9393
)
9494
return factory
9595

@@ -120,7 +120,7 @@ def _check_native_endpoint(self, endpoint):
120120
if isinstance(endpoint, dict):
121121
if "tls" in endpoint:
122122
tls = endpoint["tls"]
123-
if isinstance(tls, (dict, bool)):
123+
if isinstance(tls, dict | bool):
124124
pass
125125
elif isinstance(tls, ssl.SSLContext):
126126
pass
@@ -149,9 +149,7 @@ def _connect_transport(self, loop, transport, session_factory, done):
149149
timeout = transport.endpoint.get("timeout", 10) # in seconds
150150
if type(timeout) != int:
151151
raise ValueError(
152-
"invalid type {} for timeout in client endpoint configuration".format(
153-
type(timeout)
154-
)
152+
f"invalid type {type(timeout)} for timeout in client endpoint configuration"
155153
)
156154
# do we support HTTPS proxies?
157155

@@ -167,33 +165,25 @@ def _connect_transport(self, loop, transport, session_factory, done):
167165
version = transport.endpoint.get("version", 4)
168166
if version not in [4, 6]:
169167
raise ValueError(
170-
"invalid IP version {} in client endpoint configuration".format(
171-
version
172-
)
168+
f"invalid IP version {version} in client endpoint configuration"
173169
)
174170

175171
host = transport.endpoint["host"]
176172
if type(host) != str:
177173
raise ValueError(
178-
"invalid type {} for host in client endpoint configuration".format(
179-
type(host)
180-
)
174+
f"invalid type {type(host)} for host in client endpoint configuration"
181175
)
182176

183177
port = transport.endpoint["port"]
184178
if type(port) != int:
185179
raise ValueError(
186-
"invalid type {} for port in client endpoint configuration".format(
187-
type(port)
188-
)
180+
f"invalid type {type(port)} for port in client endpoint configuration"
189181
)
190182

191183
timeout = transport.endpoint.get("timeout", 10) # in seconds
192184
if type(timeout) != int:
193185
raise ValueError(
194-
"invalid type {} for timeout in client endpoint configuration".format(
195-
type(timeout)
196-
)
186+
f"invalid type {type(timeout)} for timeout in client endpoint configuration"
197187
)
198188

199189
tls = transport.endpoint.get("tls", None)
@@ -205,14 +195,12 @@ def _connect_transport(self, loop, transport, session_factory, done):
205195
for k in tls.keys():
206196
if k not in ["hostname", "trust_root"]:
207197
raise ValueError(
208-
"Invalid key '{}' in 'tls' config".format(k)
198+
f"Invalid key '{k}' in 'tls' config"
209199
)
210200
hostname = tls.get("hostname", host)
211201
if type(hostname) != str:
212202
raise ValueError(
213-
"invalid type {} for hostname in TLS client endpoint configuration".format(
214-
hostname
215-
)
203+
f"invalid type {hostname} for hostname in TLS client endpoint configuration"
216204
)
217205
cert_fname = tls.get("trust_root", None)
218206

@@ -234,9 +222,7 @@ def _connect_transport(self, loop, transport, session_factory, done):
234222

235223
else:
236224
raise RuntimeError(
237-
'unknown type {} for "tls" configuration in transport'.format(
238-
type(tls)
239-
)
225+
f'unknown type {type(tls)} for "tls" configuration in transport'
240226
)
241227

242228
f = loop.create_connection(

src/autobahn/asyncio/rawsocket.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,11 @@ class PrefixProtocol(asyncio.Protocol):
6161
max_length = 16 * 1024 * 1024
6262
max_length_send = max_length
6363
log = txaio.make_logger() # @UndefinedVariable
64-
peer: Optional[str] = None
65-
is_server: Optional[bool] = None
64+
peer: str | None = None
65+
is_server: bool | None = None
6666

6767
@property
68-
def transport_details(self) -> Optional[TransportDetails]:
68+
def transport_details(self) -> TransportDetails | None:
6969
"""
7070
Implements :func:`autobahn.wamp.interfaces.ITransport.transport_details`
7171
"""
@@ -221,7 +221,7 @@ def data_received(self, data):
221221
try:
222222
self.process_handshake()
223223
except HandshakeError as e:
224-
self.protocol_error("Handshake error : {err}".format(err=e))
224+
self.protocol_error(f"Handshake error : {e}")
225225
return
226226
self._handshake_done = True
227227
self._on_handshake_complete()
@@ -244,7 +244,7 @@ def data_received(self, data):
244244

245245
class HandshakeError(Exception):
246246
def __init__(self, msg, code=0):
247-
Exception.__init__(self, msg if not code else msg + " : %s" % ERRMAP.get(code))
247+
Exception.__init__(self, msg if not code else msg + f" : {ERRMAP.get(code)}")
248248

249249

250250
class RawSocketClientProtocol(RawSocketProtocol):
@@ -259,9 +259,7 @@ def process_handshake(self):
259259
raise HandshakeError("Server returned handshake error", err)
260260
if self.serializer_id != ser_id:
261261
raise HandshakeError(
262-
"Server returned different serializer {0} then requested {1}".format(
263-
ser_id, self.serializer_id
264-
)
262+
f"Server returned different serializer {ser_id} then requested {self.serializer_id}"
265263
)
266264

267265
@property
@@ -293,13 +291,13 @@ def send_response(lexp, ser_id):
293291
if not self.supports_serializer(ser_id):
294292
send_response(ERR_SERIALIZER_UNSUPPORTED, 0)
295293
raise HandshakeError(
296-
"Serializer unsupported : {ser_id}".format(ser_id=ser_id)
294+
f"Serializer unsupported : {ser_id}"
297295
)
298296
send_response(self._length_exp, ser_id)
299297

300298

301299
# this is transport independent part of WAMP protocol
302-
class WampRawSocketMixinGeneral(object):
300+
class WampRawSocketMixinGeneral:
303301
def _on_handshake_complete(self):
304302
self.log.debug("WampRawSocketProtocol: Handshake complete")
305303
# RawSocket connection established. Now let the user WAMP session factory
@@ -364,9 +362,7 @@ def send(self, msg):
364362
except Exception as e:
365363
# all exceptions raised from above should be serialization errors ..
366364
raise SerializationError(
367-
"WampRawSocketProtocol: unable to serialize WAMP application payload ({0})".format(
368-
e
369-
)
365+
f"WampRawSocketProtocol: unable to serialize WAMP application payload ({e})"
370366
)
371367
else:
372368
self.sendString(payload)
@@ -385,7 +381,7 @@ def isOpen(self):
385381

386382

387383
# this is asyncio dependent part of WAMP protocol
388-
class WampRawSocketMixinAsyncio(object):
384+
class WampRawSocketMixinAsyncio:
389385
"""
390386
Base class for asyncio-based WAMP-over-RawSocket protocols.
391387
"""
@@ -474,7 +470,7 @@ def serializer_id(self):
474470
return self._serializer.RAWSOCKET_SERIALIZER_ID
475471

476472

477-
class WampRawSocketFactory(object):
473+
class WampRawSocketFactory:
478474
"""
479475
Adapter class for asyncio-based WebSocket client and server factories.def dataReceived(self, data):
480476
"""

src/autobahn/asyncio/util.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141

4242

4343
def transport_channel_id(
44-
transport, is_server: bool, channel_id_type: Optional[str] = None
44+
transport, is_server: bool, channel_id_type: str | None = None
4545
) -> bytes:
4646
"""
4747
Application-layer user authentication protocols are vulnerable to generic
@@ -63,7 +63,7 @@ def transport_channel_id(
6363

6464
# ssl.CHANNEL_BINDING_TYPES
6565
if channel_id_type not in ["tls-unique"]:
66-
raise Exception("invalid channel ID type {}".format(channel_id_type))
66+
raise Exception(f"invalid channel ID type {channel_id_type}")
6767

6868
ssl_obj = transport.get_extra_info("ssl_object")
6969
if ssl_obj is None:
@@ -96,24 +96,24 @@ def peer2str(transport: asyncio.transports.BaseTransport) -> str:
9696
peer = transport.get_extra_info("peername")
9797
if isinstance(peer, tuple):
9898
ip_ver = 4 if len(peer) == 2 else 6
99-
return "tcp{2}:{0}:{1}".format(peer[0], peer[1], ip_ver)
99+
return f"tcp{ip_ver}:{peer[0]}:{peer[1]}"
100100
elif isinstance(peer, str):
101-
return "unix:{0}".format(peer)
101+
return f"unix:{peer}"
102102
else:
103-
return "?:{0}".format(peer)
103+
return f"?:{peer}"
104104
except:
105105
pass
106106

107107
try:
108108
proc: Popen = transport.get_extra_info("subprocess")
109109
# return 'process:{}'.format(transport.pid)
110-
return "process:{}".format(proc.pid)
110+
return f"process:{proc.pid}"
111111
except:
112112
pass
113113

114114
try:
115115
pipe = transport.get_extra_info("pipe")
116-
return "pipe:{}".format(pipe)
116+
return f"pipe:{pipe}"
117117
except:
118118
pass
119119

src/autobahn/asyncio/wamp.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class ApplicationSessionFactory(protocol.ApplicationSessionFactory):
8383

8484

8585
@public
86-
class ApplicationRunner(object):
86+
class ApplicationRunner:
8787
"""
8888
This class is a convenience tool mainly for development and quick hosting
8989
of WAMP application components.
@@ -179,7 +179,7 @@ def create():
179179
session = make(cfg)
180180
except Exception as e:
181181
self.log.error(
182-
"ApplicationSession could not be instantiated: {}".format(e)
182+
f"ApplicationSession could not be instantiated: {e}"
183183
)
184184
loop = asyncio.get_event_loop()
185185
if loop.is_running():
@@ -249,9 +249,8 @@ def accept(response):
249249
else:
250250
if self.ssl and not isSecure:
251251
raise RuntimeError(
252-
'ssl argument value passed to %s conflicts with the "ws:" '
252+
f'ssl argument value passed to {self.__class__.__name__} conflicts with the "ws:" '
253253
'prefix of the url argument. Did you mean to use "wss:"?'
254-
% self.__class__.__name__
255254
)
256255
ssl = self.ssl
257256

src/autobahn/asyncio/websocket.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ class WebSocketAdapterProtocol(asyncio.Protocol):
6666

6767
log = txaio.make_logger()
6868

69-
peer: Optional[str] = None
70-
is_server: Optional[bool] = None
69+
peer: str | None = None
70+
is_server: bool | None = None
7171

7272
def connection_made(self, transport):
7373
# asyncio networking framework entry point, called by asyncio
@@ -240,7 +240,7 @@ def startTLS(self):
240240
raise Exception("WSS over explicit proxies not implemented")
241241

242242

243-
class WebSocketAdapterFactory(object):
243+
class WebSocketAdapterFactory:
244244
"""
245245
Adapter class for asyncio-based WebSocket client and server factories.
246246
"""

0 commit comments

Comments
 (0)