From 62194d33b63b21f64795ecf6b4f62e3acd21f3db Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 May 2024 17:09:50 +0000 Subject: [PATCH 1/2] [pre-commit.ci] pre-commit autoupdate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.3.2 → v0.4.3](https://github.com/astral-sh/ruff-pre-commit/compare/v0.3.2...v0.4.3) - [github.com/pre-commit/mirrors-mypy: v1.9.0 → v1.10.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.9.0...v1.10.0) - [github.com/pre-commit/pre-commit-hooks: v4.5.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.5.0...v4.6.0) --- .pre-commit-config.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5e7460c17..0b609a417 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,7 +26,7 @@ repos: # autoformat and lint Python code - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.3.2 + rev: v0.4.3 hooks: - id: ruff types_or: @@ -43,7 +43,7 @@ repos: exclude: zmq/constants.py - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.9.0 + rev: v1.10.0 hooks: - id: mypy files: zmq/.* @@ -55,7 +55,7 @@ repos: additional_dependencies: - types-paramiko - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.5.0 + rev: v4.6.0 hooks: - id: end-of-file-fixer - id: check-executables-have-shebangs From 543774e36de7847d44f51e9f2a13133b844e074d Mon Sep 17 00:00:00 2001 From: Min RK Date: Mon, 6 May 2024 21:50:53 +0200 Subject: [PATCH 2/2] apply ruff fixes --- buildutils/constants.py | 6 +++--- .../asyncio/helloworld_pubsub_dealerrouter.py | 4 ++-- examples/device/device.py | 4 ++-- examples/draft/client-server.py | 2 +- examples/eventloop/asyncweb.py | 4 ++-- examples/heartbeat/heartbeater.py | 2 +- examples/mongodb/controller.py | 8 ++++---- examples/monitoring/simple_monitor.py | 2 +- examples/monitoring/zmq_monitor_class.py | 4 ++-- examples/pubsub/topics_sub.py | 2 +- perf/collect.py | 2 +- perf/perf.py | 8 ++++---- zmq/_future.py | 4 ++-- zmq/auth/certs.py | 2 +- zmq/backend/__init__.py | 2 +- zmq/backend/cffi/_poll.py | 4 ++-- zmq/backend/cffi/socket.py | 2 +- zmq/backend/cython/_zmq.py | 16 ++++++++-------- zmq/error.py | 2 +- zmq/eventloop/zmqstream.py | 5 ++--- zmq/green/poll.py | 2 +- zmq/ssh/tunnel.py | 10 +++++----- zmq/sugar/frame.py | 2 +- zmq/sugar/socket.py | 4 ++-- zmq/sugar/tracker.py | 2 +- zmq/tests/test_device.py | 4 ++-- zmq/tests/test_socket.py | 6 +++--- zmq/utils/interop.py | 2 +- zmq/utils/monitor.py | 2 +- zmq/utils/strtypes.py | 4 ++-- zmqversion.py | 12 ++++++------ 31 files changed, 67 insertions(+), 68 deletions(-) diff --git a/buildutils/constants.py b/buildutils/constants.py index 59d8b0308..07f276b02 100644 --- a/buildutils/constants.py +++ b/buildutils/constants.py @@ -61,7 +61,7 @@ def ifndefs(): lines = ['#define _PYZMQ_UNDEFINED (-9999)'] for name in all_names: if not no_prefix(name): - name = 'ZMQ_%s' % name + name = f'ZMQ_{name}' lines.append(ifndef_t.format(name)) return dict(ZMQ_IFNDEFS='\n'.join(lines)) @@ -104,11 +104,11 @@ def promoted_constants(): def generate_file(fname, ns_func, dest_dir="."): """generate a constants file from its template""" - with open(pjoin(root, 'buildutils', 'templates', '%s' % fname)) as f: + with open(pjoin(root, 'buildutils', 'templates', f'{fname}')) as f: tpl = f.read() out = tpl.format(**ns_func()) dest = pjoin(dest_dir, fname) - print("generating %s from template" % dest) + print(f"generating {dest} from template") with open(dest, 'w') as f: f.write(out) if fname.endswith(".py"): diff --git a/examples/asyncio/helloworld_pubsub_dealerrouter.py b/examples/asyncio/helloworld_pubsub_dealerrouter.py index c0ce104fa..743545ba6 100644 --- a/examples/asyncio/helloworld_pubsub_dealerrouter.py +++ b/examples/asyncio/helloworld_pubsub_dealerrouter.py @@ -48,8 +48,8 @@ def msg_sub(self, msg: str) -> None: class HelloWorldMessage: def __init__(self, url: str = '127.0.0.1', port: int = 5555): # get ZeroMQ version - print("Current libzmq version is %s" % zmq.zmq_version()) - print("Current pyzmq version is %s" % zmq.__version__) + print(f"Current libzmq version is {zmq.zmq_version()}") + print(f"Current pyzmq version is {zmq.__version__}") self.url = f"tcp://{url}:{port}" # pub/sub and dealer/router diff --git a/examples/device/device.py b/examples/device/device.py index 241723bb0..b10d59eb9 100644 --- a/examples/device/device.py +++ b/examples/device/device.py @@ -17,11 +17,11 @@ def produce(url, ident): ctx = zmq.Context.instance() s = ctx.socket(zmq.PUSH) s.connect(url) - print("Producing %s" % ident) + print(f"Producing {ident}") for i in range(MSGS): s.send(('%s: %i' % (ident, time.time())).encode('utf8')) time.sleep(1) - print("Producer %s done" % ident) + print(f"Producer {ident} done") s.close() diff --git a/examples/draft/client-server.py b/examples/draft/client-server.py index 86cad3334..6a5924422 100644 --- a/examples/draft/client-server.py +++ b/examples/draft/client-server.py @@ -16,7 +16,7 @@ print(f'server recvd {msg.bytes!r} from {msg.routing_id!r}') server.send_string('reply %i' % i, routing_id=msg.routing_id) reply = client.recv_string() - print('client recvd %r' % reply) + print(f'client recvd {reply!r}') time.sleep(0.1) client.close() diff --git a/examples/eventloop/asyncweb.py b/examples/eventloop/asyncweb.py index 048e1a4f7..b1a377786 100644 --- a/examples/eventloop/asyncweb.py +++ b/examples/eventloop/asyncweb.py @@ -29,7 +29,7 @@ def slow_responder() -> None: i = 0 while True: frame, msg = socket.recv_multipart() - print("\nworker received %r\n" % msg, end='') + print(f"\nworker received {msg!r}\n", end='') time.sleep(random.randint(1, 5)) socket.send_multipart([frame, msg + b" to you too, #%i" % i]) i += 1 @@ -52,7 +52,7 @@ async def get(self) -> None: # finish web request with worker's reply reply = await s.recv_string() - print("\nfinishing with %r\n" % reply) + print(f"\nfinishing with {reply!r}\n") self.write(reply) diff --git a/examples/heartbeat/heartbeater.py b/examples/heartbeat/heartbeater.py index d6a8032b1..7552af818 100644 --- a/examples/heartbeat/heartbeater.py +++ b/examples/heartbeat/heartbeater.py @@ -80,7 +80,7 @@ def handle_pong(self, msg): if msg[1] == str(self.lifetime): self.responses.add(msg[0]) else: - print("got bad heartbeat (possibly old?): %s" % msg[1]) + print(f"got bad heartbeat (possibly old?): {msg[1]}") # sub.setsockopt(zmq.SUBSCRIBE) diff --git a/examples/mongodb/controller.py b/examples/mongodb/controller.py index 5768985dc..ecbb34182 100644 --- a/examples/mongodb/controller.py +++ b/examples/mongodb/controller.py @@ -47,7 +47,7 @@ def add_document(self, doc: Dict) -> Optional[str]: try: self._table.insert(doc) except Exception as e: - return 'Error: %s' % e + return f'Error: {e}' return None def get_document_by_keys(self, keys: Dict[str, Any]) -> Union[Dict, str, None]: @@ -55,11 +55,11 @@ def get_document_by_keys(self, keys: Dict[str, Any]) -> Union[Dict, str, None]: Attempts to return a single document from database table that matches each key/value in keys dictionary. """ - print('attempting to retrieve document using keys: %s' % keys) + print(f'attempting to retrieve document using keys: {keys}') try: return self._table.find_one(keys) except Exception as e: - return 'Error: %s' % e + return f'Error: {e}' def start(self) -> None: context = zmq.Context() @@ -69,7 +69,7 @@ def start(self) -> None: msg = socket.recv_multipart() print("Received msg: ", msg) if len(msg) != 3: - error_msg = 'invalid message received: %s' % msg + error_msg = f'invalid message received: {msg}' print(error_msg) reply = [msg[0], error_msg] socket.send_multipart(reply) diff --git a/examples/monitoring/simple_monitor.py b/examples/monitoring/simple_monitor.py index 6a5a4fe7a..dc96af244 100644 --- a/examples/monitoring/simple_monitor.py +++ b/examples/monitoring/simple_monitor.py @@ -20,7 +20,7 @@ def line() -> None: print('-' * 40) -print("libzmq-%s" % zmq.zmq_version()) +print(f"libzmq-{zmq.zmq_version()}") if zmq.zmq_version_info() < (4, 0): raise RuntimeError("monitoring in libzmq version < 4.0 is not supported") diff --git a/examples/monitoring/zmq_monitor_class.py b/examples/monitoring/zmq_monitor_class.py index c336af4c8..a9f0cbbb9 100644 --- a/examples/monitoring/zmq_monitor_class.py +++ b/examples/monitoring/zmq_monitor_class.py @@ -50,7 +50,7 @@ def event_monitor_thread_async( monitor: a zmq monitor socket, from calling: my_zmq_socket.get_monitor_socket() loop: an asyncio event loop, from calling zmq.asyncio.asyncio.get_event_loop() , whens starting a thread it does not contains an event loop """ - print("libzmq-%s" % zmq.zmq_version()) + print(f"libzmq-{zmq.zmq_version()}") if zmq.zmq_version_info() < (4, 0): raise RuntimeError("monitoring in libzmq version < 4.0 is not supported") @@ -99,7 +99,7 @@ def event_monitor_thread(monitor: zmq.Socket) -> None: monitor: a zmq monitor socket, from calling: my_zmq_socket.get_monitor_socket() """ - print("libzmq-%s" % zmq.zmq_version()) + print(f"libzmq-{zmq.zmq_version()}") if zmq.zmq_version_info() < (4, 0): raise RuntimeError("monitoring in libzmq version < 4.0 is not supported") diff --git a/examples/pubsub/topics_sub.py b/examples/pubsub/topics_sub.py index 56ec38387..d4e070076 100755 --- a/examples/pubsub/topics_sub.py +++ b/examples/pubsub/topics_sub.py @@ -38,7 +38,7 @@ def main() -> None: print("Receiving messages on ALL topics...") s.setsockopt(zmq.SUBSCRIBE, b'') else: - print("Receiving messages on topics: %s ..." % topics) + print(f"Receiving messages on topics: {topics} ...") for t in topics: s.setsockopt(zmq.SUBSCRIBE, t.encode('utf-8')) print diff --git a/perf/collect.py b/perf/collect.py index ee9500330..2594c96b2 100644 --- a/perf/collect.py +++ b/perf/collect.py @@ -106,7 +106,7 @@ def main(): test = args.test full_name = full_names[test] - print("Running %s test" % full_name) + print(f"Running {full_name} test") fname = test + '.pickle' import pandas as pd diff --git a/perf/perf.py b/perf/perf.py index 81d6cd67b..7e35e9624 100644 --- a/perf/perf.py +++ b/perf/perf.py @@ -218,10 +218,10 @@ def throughput(url, count, size, poll=False, copy=True, quiet=False): if not quiet: print("message size : %8i [B]" % size) print("message count : %8i [msgs]" % count) - print("send only : %8.0f [msg/s]" % send_throughput) - print("mean throughput: %8.0f [msg/s]" % throughput) - print("mean throughput: %12.3f [Mb/s]" % megabits) - print("test time : %12.3f [s]" % elapsed) + print(f"send only : {send_throughput:8.0f} [msg/s]") + print(f"mean throughput: {throughput:8.0f} [msg/s]") + print(f"mean throughput: {megabits:12.3f} [Mb/s]") + print(f"test time : {elapsed:12.3f} [s]") ctx.destroy() return (send_throughput, throughput) diff --git a/zmq/_future.py b/zmq/_future.py index 052f8f6b5..effd0d564 100644 --- a/zmq/_future.py +++ b/zmq/_future.py @@ -622,7 +622,7 @@ def _handle_recv(self): elif kind == 'recv': recv = self._shadow_sock.recv else: - raise ValueError("Unhandled recv event type: %r" % kind) + raise ValueError(f"Unhandled recv event type: {kind!r}") kwargs['flags'] |= _zmq.DONTWAIT try: @@ -662,7 +662,7 @@ def _handle_send(self): elif kind == 'send': send = self._shadow_sock.send else: - raise ValueError("Unhandled send event type: %r" % kind) + raise ValueError(f"Unhandled send event type: {kind!r}") kwargs['flags'] |= _zmq.DONTWAIT try: diff --git a/zmq/auth/certs.py b/zmq/auth/certs.py index 7db1b55c5..d60ae005d 100644 --- a/zmq/auth/certs.py +++ b/zmq/auth/certs.py @@ -116,7 +116,7 @@ def load_certificate( break if public_key is None: - raise ValueError("No public key found in %s" % filename) + raise ValueError(f"No public key found in {filename}") return public_key, secret_key diff --git a/zmq/backend/__init__.py b/zmq/backend/__init__.py index 39640819e..15f696d9d 100644 --- a/zmq/backend/__init__.py +++ b/zmq/backend/__init__.py @@ -11,7 +11,7 @@ if 'PYZMQ_BACKEND' in os.environ: backend = os.environ['PYZMQ_BACKEND'] if backend in ('cython', 'cffi'): - backend = 'zmq.backend.%s' % backend + backend = f'zmq.backend.{backend}' _ns = select_backend(backend) else: # default to cython, fallback to cffi diff --git a/zmq/backend/cffi/_poll.py b/zmq/backend/cffi/_poll.py index 34734b63e..63e2763b9 100644 --- a/zmq/backend/cffi/_poll.py +++ b/zmq/backend/cffi/_poll.py @@ -65,8 +65,8 @@ def zmq_poll(sockets, timeout): # don't allow negative ms_passed, # which can happen on old Python versions without time.monotonic. warnings.warn( - "Negative elapsed time for interrupted poll: %s." - " Did the clock change?" % ms_passed, + f"Negative elapsed time for interrupted poll: {ms_passed}." + " Did the clock change?", RuntimeWarning, ) ms_passed = 0 diff --git a/zmq/backend/cffi/socket.py b/zmq/backend/cffi/socket.py index 4b998d300..2d21e10d0 100644 --- a/zmq/backend/cffi/socket.py +++ b/zmq/backend/cffi/socket.py @@ -220,7 +220,7 @@ def set(self, option, value): if isinstance(value, bytes): if opt_type != _OptType.bytes: - raise TypeError("not a bytes sockopt: %s" % option) + raise TypeError(f"not a bytes sockopt: {option}") length = len(value) c_value_pointer, c_sizet = initialize_opt_pointer(option, value, length) diff --git a/zmq/backend/cython/_zmq.py b/zmq/backend/cython/_zmq.py index fb6f3b6f3..3052afcbd 100644 --- a/zmq/backend/cython/_zmq.py +++ b/zmq/backend/cython/_zmq.py @@ -755,13 +755,13 @@ def set(self, option: C.int, optval): if opt_type == _OptType.bytes: if not isinstance(optval, bytes): - raise TypeError('expected bytes, got: %r' % optval) + raise TypeError(f'expected bytes, got: {optval!r}') optval_c = PyBytes_AsString(optval) sz = PyBytes_Size(optval) _setsockopt(self.handle, option, optval_c, sz) elif opt_type == _OptType.int64: if not isinstance(optval, int): - raise TypeError('expected int, got: %r' % optval) + raise TypeError(f'expected int, got: {optval!r}') optval_int64_c = optval _setsockopt(self.handle, option, address(optval_int64_c), sizeof(int64_t)) else: @@ -771,7 +771,7 @@ def set(self, option: C.int, optval): # sockopts will still raise just the same, but it will be libzmq doing # the raising. if not isinstance(optval, int): - raise TypeError('expected int, got: %r' % optval) + raise TypeError(f'expected int, got: {optval!r}') optval_int_c = optval _setsockopt(self.handle, option, address(optval_int_c), sizeof(int)) @@ -876,7 +876,7 @@ def bind(self, addr): addr = addr_b.decode('utf-8') if not isinstance(addr_b, bytes): - raise TypeError('expected str, got: %r' % addr) + raise TypeError(f'expected str, got: {addr!r}') c_addr = addr_b rc = zmq_bind(self.handle, c_addr) if rc != 0: @@ -921,7 +921,7 @@ def connect(self, addr): if isinstance(addr, str): addr = addr.encode('utf-8') if not isinstance(addr, bytes): - raise TypeError('expected str, got: %r' % addr) + raise TypeError(f'expected str, got: {addr!r}') c_addr = addr while True: @@ -957,7 +957,7 @@ def unbind(self, addr): if isinstance(addr, str): addr = addr.encode('utf-8') if not isinstance(addr, bytes): - raise TypeError('expected str, got: %r' % addr) + raise TypeError(f'expected str, got: {addr!r}') c_addr = addr rc = zmq_unbind(self.handle, c_addr) @@ -987,7 +987,7 @@ def disconnect(self, addr): if isinstance(addr, str): addr = addr.encode('utf-8') if not isinstance(addr, bytes): - raise TypeError('expected str, got: %r' % addr) + raise TypeError(f'expected str, got: {addr!r}') c_addr = addr rc = zmq_disconnect(self.handle, c_addr) @@ -1523,7 +1523,7 @@ def zmq_poll(sockets, timeout: C.int = -1): free(pollitems) raise TypeError( "Socket must be a 0MQ socket, an integer fd or have " - "a fileno() method: %r" % s + f"a fileno() method: {s!r}" ) ms_passed: int = 0 diff --git a/zmq/error.py b/zmq/error.py index 6e85b8704..6184b578e 100644 --- a/zmq/error.py +++ b/zmq/error.py @@ -172,7 +172,7 @@ def __init__(self, min_version: str, msg: str = "Feature"): self.version = _zmq_version def __repr__(self): - return "ZMQVersionError('%s')" % str(self) + return f"ZMQVersionError('{str(self)}')" def __str__(self): return f"{self.msg} requires libzmq >= {self.min_version}, have {self.version}" diff --git a/zmq/eventloop/zmqstream.py b/zmq/eventloop/zmqstream.py index 36ce14109..c7138a7c7 100644 --- a/zmq/eventloop/zmqstream.py +++ b/zmq/eventloop/zmqstream.py @@ -522,10 +522,9 @@ def close(self, linger: int | None = None) -> None: # hopefully this happened promptly after close, # otherwise somebody else may have the FD warnings.warn( - "Unregistering FD %s after closing socket. " + f"Unregistering FD {self._fd} after closing socket. " "This could result in unregistering handlers for the wrong socket. " - "Please use stream.close() instead of closing the socket directly." - % self._fd, + "Please use stream.close() instead of closing the socket directly.", stacklevel=2, ) self.io_loop.remove_handler(self._fd) diff --git a/zmq/green/poll.py b/zmq/green/poll.py index 5060740ae..7aa1bedd4 100644 --- a/zmq/green/poll.py +++ b/zmq/green/poll.py @@ -38,7 +38,7 @@ def _get_descriptors(self): else: raise TypeError( 'Socket must be a 0MQ socket, an integer fd ' - 'or have a fileno() method: %r' % socket + f'or have a fileno() method: {socket!r}' ) if flags & zmq.POLLIN: diff --git a/zmq/ssh/tunnel.py b/zmq/ssh/tunnel.py index 4645f9797..fd62cd8ba 100644 --- a/zmq/ssh/tunnel.py +++ b/zmq/ssh/tunnel.py @@ -249,7 +249,7 @@ def openssh_tunnel( if ':' in server: server, port = server.split(':') - ssh += " -p %s" % port + ssh += f" -p {port}" cmd = f"{ssh} -O check {server}" (output, exitstatus) = pexpect.run(cmd, withexitstatus=True) @@ -297,7 +297,7 @@ def openssh_tunnel( print(tunnel.exitstatus) print(tunnel.before) print(tunnel.after) - raise RuntimeError("tunnel '%s' failed to start" % (cmd)) + raise RuntimeError(f"tunnel '{cmd}' failed to start") else: return tunnel.pid else: @@ -305,7 +305,7 @@ def openssh_tunnel( print("Password rejected, try again") password = None if password is None: - password = getpass("%s's password: " % (server)) + password = getpass(f"{server}'s password: ") tunnel.sendline(password) failed = True raise MaxRetryExceeded(f"Failed after {MAX_RETRY} attempts") @@ -375,7 +375,7 @@ def paramiko_tunnel( if password is None: if not _try_passwordless_paramiko(server, keyfile): - password = getpass("%s's password: " % (server)) + password = getpass(f"{server}'s password: ") p = Process( target=_paramiko_tunnel, @@ -424,7 +424,7 @@ def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None print('SIGINT: Port forwarding stopped cleanly') sys.exit(0) except Exception as e: - print("Port forwarding stopped uncleanly: %s" % e) + print(f"Port forwarding stopped uncleanly: {e}") sys.exit(255) diff --git a/zmq/sugar/frame.py b/zmq/sugar/frame.py index ccab7d673..39587433c 100644 --- a/zmq/sugar/frame.py +++ b/zmq/sugar/frame.py @@ -13,7 +13,7 @@ def _draft(v, feature): zmq.error._check_version(v, feature) if not zmq.DRAFT_API: raise RuntimeError( - "libzmq and pyzmq must be built with draft support for %s" % feature + f"libzmq and pyzmq must be built with draft support for {feature}" ) diff --git a/zmq/sugar/socket.py b/zmq/sugar/socket.py index fbd5390a4..e5e253a34 100644 --- a/zmq/sugar/socket.py +++ b/zmq/sugar/socket.py @@ -496,7 +496,7 @@ def bind_to_random_port( ): # if LAST_ENDPOINT is supported, and min_port / max_port weren't specified, # we can bind to port 0 and let the OS do the work - self.bind("%s:*" % addr) + self.bind(f"{addr}:*") url = cast(bytes, self.last_endpoint).decode('ascii', 'replace') _, port_s = url.rsplit(':', 1) return int(port_s) @@ -1074,7 +1074,7 @@ def get_monitor_socket( # safe-guard, method only available on libzmq >= 4 if zmq.zmq_version_info() < (4,): raise NotImplementedError( - "get_monitor_socket requires libzmq >= 4, have %s" % zmq.zmq_version() + f"get_monitor_socket requires libzmq >= 4, have {zmq.zmq_version()}" ) # if already monitoring, return existing socket diff --git a/zmq/sugar/tracker.py b/zmq/sugar/tracker.py index 1887906a3..973fdbd6e 100644 --- a/zmq/sugar/tracker.py +++ b/zmq/sugar/tracker.py @@ -54,7 +54,7 @@ def __init__(self, *towatch: tuple[MessageTracker | Event | Frame]): raise ValueError("Not a tracked message") self.peers.add(obj.tracker) else: - raise TypeError("Require Events or Message Frames, not %s" % type(obj)) + raise TypeError(f"Require Events or Message Frames, not {type(obj)}") @property def done(self): diff --git a/zmq/tests/test_device.py b/zmq/tests/test_device.py index 343d51dd7..bc2dbf79e 100644 --- a/zmq/tests/test_device.py +++ b/zmq/tests/test_device.py @@ -29,7 +29,7 @@ def test_device_attributes(self): def test_single_socket_forwarder_connect(self): if zmq.zmq_version() in ('4.1.1', '4.0.6'): - raise SkipTest("libzmq-%s broke single-socket devices" % zmq.zmq_version()) + raise SkipTest(f"libzmq-{zmq.zmq_version()} broke single-socket devices") dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1) req = self.context.socket(zmq.REQ) port = req.bind_to_random_port('tcp://127.0.0.1') @@ -55,7 +55,7 @@ def test_single_socket_forwarder_connect(self): def test_single_socket_forwarder_bind(self): if zmq.zmq_version() in ('4.1.1', '4.0.6'): - raise SkipTest("libzmq-%s broke single-socket devices" % zmq.zmq_version()) + raise SkipTest(f"libzmq-{zmq.zmq_version()} broke single-socket devices") dev = devices.ThreadDevice(zmq.QUEUE, zmq.REP, -1) port = dev.bind_in_to_random_port('tcp://127.0.0.1') req = self.context.socket(zmq.REQ) diff --git a/zmq/tests/test_socket.py b/zmq/tests/test_socket.py index 598799731..3c1beef35 100644 --- a/zmq/tests/test_socket.py +++ b/zmq/tests/test_socket.py @@ -486,7 +486,7 @@ def test_ipc_path_max_length(self): if zmq.IPC_PATH_MAX_LEN == 0: raise SkipTest("IPC_PATH_MAX_LEN undefined") - msg = "Surprising value for IPC_PATH_MAX_LEN: %s" % zmq.IPC_PATH_MAX_LEN + msg = f"Surprising value for IPC_PATH_MAX_LEN: {zmq.IPC_PATH_MAX_LEN}" assert zmq.IPC_PATH_MAX_LEN > 30, msg assert zmq.IPC_PATH_MAX_LEN < 1025, msg @@ -619,13 +619,13 @@ def test_large_send(self): try: buf = c * N except MemoryError as e: - raise SkipTest("Not enough memory: %s" % e) + raise SkipTest(f"Not enough memory: {e}") a, b = self.create_bound_pair() try: a.send(buf, copy=False) rcvd = b.recv(copy=False) except MemoryError as e: - raise SkipTest("Not enough memory: %s" % e) + raise SkipTest(f"Not enough memory: {e}") # sample the front and back of the received message # without checking the whole content byte = ord(c) diff --git a/zmq/utils/interop.py b/zmq/utils/interop.py index 7a34a73cc..ab4ffd9a8 100644 --- a/zmq/utils/interop.py +++ b/zmq/utils/interop.py @@ -26,4 +26,4 @@ def cast_int_addr(n: Any) -> int: if isinstance(n, ffi.CData): return int(ffi.cast("size_t", n)) - raise ValueError("Cannot cast %r to int" % n) + raise ValueError(f"Cannot cast {n!r} to int") diff --git a/zmq/utils/monitor.py b/zmq/utils/monitor.py index 1adeb53ea..f549052b5 100644 --- a/zmq/utils/monitor.py +++ b/zmq/utils/monitor.py @@ -42,7 +42,7 @@ def parse_monitor_message(msg: list[bytes]) -> _MonitorMessage: event description as dict with the keys `event`, `value`, and `endpoint`. """ if len(msg) != 2 or len(msg[0]) != 6: - raise RuntimeError("Invalid event message format: %s" % msg) + raise RuntimeError(f"Invalid event message format: {msg}") event_id, value = struct.unpack("=hi", msg[0]) event: _MonitorMessage = { 'event': zmq.Event(event_id), diff --git a/zmq/utils/strtypes.py b/zmq/utils/strtypes.py index 333167192..3d90a0480 100644 --- a/zmq/utils/strtypes.py +++ b/zmq/utils/strtypes.py @@ -27,7 +27,7 @@ def cast_bytes(s, encoding='utf8', errors='strict'): elif isinstance(s, str): return s.encode(encoding, errors) else: - raise TypeError("Expected unicode or bytes, got %r" % s) + raise TypeError(f"Expected unicode or bytes, got {s!r}") def cast_unicode(s, encoding='utf8', errors='strict'): @@ -42,7 +42,7 @@ def cast_unicode(s, encoding='utf8', errors='strict'): elif isinstance(s, str): return s else: - raise TypeError("Expected unicode or bytes, got %r" % s) + raise TypeError(f"Expected unicode or bytes, got {s!r}") # give short 'b' alias for cast_bytes, so that we can use fake b'stuff' diff --git a/zmqversion.py b/zmqversion.py index a74894bd7..6717a5fce 100644 --- a/zmqversion.py +++ b/zmqversion.py @@ -88,16 +88,16 @@ def check_zmq_version(min_version): found, zmq_h = find_zmq_version() sf = ver_str(found) if found < min_version: - print("This pyzmq requires zeromq >= %s" % sv) - print("but it appears you are building against %s" % zmq_h) - print("which has zeromq %s" % sf) + print(f"This pyzmq requires zeromq >= {sv}") + print(f"but it appears you are building against {zmq_h}") + print(f"which has zeromq {sf}") sys.exit(1) except OSError: msg = '\n'.join( [ "Couldn't find zmq.h to check for version compatibility.", "If you see 'undeclared identifier' errors, your ZeroMQ is likely too old.", - "This pyzmq requires zeromq >= %s" % sv, + f"This pyzmq requires zeromq >= {sv}", ] ) warn(msg) @@ -107,7 +107,7 @@ def check_zmq_version(min_version): "Couldn't find ZMQ_VERSION macros in zmq.h to check for version compatibility.", "This probably means that you have ZeroMQ <= 2.0.9", "If you see 'undeclared identifier' errors, your ZeroMQ is likely too old.", - "This pyzmq requires zeromq >= %s" % sv, + f"This pyzmq requires zeromq >= {sv}", ] ) warn(msg) @@ -117,7 +117,7 @@ def check_zmq_version(min_version): [ "Unexpected Error checking for zmq version.", "If you see 'undeclared identifier' errors, your ZeroMQ is likely too old.", - "This pyzmq requires zeromq >= %s" % sv, + f"This pyzmq requires zeromq >= {sv}", ] ) warn(msg)