diff --git a/.github/release_log.py b/.github/release_log.py old mode 100644 new mode 100755 diff --git a/docs/conf.py b/docs/conf.py old mode 100644 new mode 100755 diff --git a/examples/bench/echoclient.py b/examples/bench/echoclient.py index 711b2f11..dbca1d26 100644 --- a/examples/bench/echoclient.py +++ b/examples/bench/echoclient.py @@ -45,7 +45,7 @@ addr = args.addr.split(':') addr[1] = int(addr[1]) addr = tuple(addr) - print('will connect to: {}'.format(addr)) + print(f'will connect to: {addr}') MSGSIZE = args.msize REQSIZE = MSGSIZE * args.mpr diff --git a/examples/bench/echoserver.py b/examples/bench/echoserver.py index 906ca85a..fdf7811a 100644 --- a/examples/bench/echoserver.py +++ b/examples/bench/echoserver.py @@ -5,6 +5,7 @@ import pathlib import socket import ssl +import sys PRINT = 0 @@ -138,7 +139,7 @@ async def print_debug(loop): addr[1] = int(addr[1]) addr = tuple(addr) - print('serving on: {}'.format(addr)) + print(f'serving on: {addr}') server_context = None if args.ssl: @@ -159,11 +160,11 @@ async def print_debug(loop): if args.streams: if args.proto: print('cannot use --stream and --proto simultaneously') - exit(1) + sys.exit(1) if args.buffered: print('cannot use --stream and --buffered simultaneously') - exit(1) + sys.exit(1) print('using asyncio/streams') if unix: @@ -178,7 +179,7 @@ async def print_debug(loop): elif args.proto: if args.streams: print('cannot use --stream and --proto simultaneously') - exit(1) + sys.exit(1) if args.buffered: print('using buffered protocol') @@ -197,7 +198,7 @@ async def print_debug(loop): else: if args.ssl: print('cannot use SSL for loop.sock_* methods') - exit(1) + sys.exit(1) print('using sock_recv/sock_sendall') loop.create_task(echo_server(loop, addr, unix)) diff --git a/examples/bench/rlserver.py b/examples/bench/rlserver.py index 90b84bee..3092f28c 100644 --- a/examples/bench/rlserver.py +++ b/examples/bench/rlserver.py @@ -71,7 +71,7 @@ async def print_debug(loop): addr = tuple(addr) print('readline performance test') - print('serving on: {}'.format(addr)) + print(f'serving on: {addr}') print('using asyncio/streams') if unix: diff --git a/setup.py b/setup.py index 32d94ae8..df29900d 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ if vi < (3, 8): raise RuntimeError('uvloop requires Python 3.8 or greater') -if sys.platform in ('win32', 'cygwin', 'cli'): +if sys.platform in {'win32', 'cygwin', 'cli'}: raise RuntimeError('uvloop does not support Windows at the moment') import os @@ -26,7 +26,7 @@ MODULES_CFLAGS = [os.getenv('UVLOOP_OPT_CFLAGS', '-O2')] _ROOT = pathlib.Path(__file__).parent LIBUV_DIR = str(_ROOT / 'vendor' / 'libuv') -LIBUV_BUILD_DIR = str(_ROOT / 'build' / 'libuv-{}'.format(MACHINE)) +LIBUV_BUILD_DIR = str(_ROOT / 'build' / f'libuv-{MACHINE}') def _libuv_build_env(): @@ -118,15 +118,16 @@ def finalize_options(self): import Cython except ImportError: raise RuntimeError( - 'please install {} to compile uvloop from source'.format( - CYTHON_DEPENDENCY)) + f'please install {CYTHON_DEPENDENCY} to compile uvloop ' + 'from source' + ) cython_dep = pkg_resources.Requirement.parse(CYTHON_DEPENDENCY) if Cython.__version__ not in cython_dep: raise RuntimeError( - 'uvloop requires {}, got Cython=={}'.format( - CYTHON_DEPENDENCY, Cython.__version__ - )) + f'uvloop requires {CYTHON_DEPENDENCY}, ' + f'got Cython=={Cython.__version__}' + ) from Cython.Build import cythonize @@ -183,7 +184,7 @@ def build_libuv(self): njobs = len(os.sched_getaffinity(0)) except AttributeError: njobs = os.cpu_count() - j_flag = '-j{}'.format(njobs or 1) + j_flag = f'-j{njobs or 1}' c_flag = "CFLAGS={}".format(env['CFLAGS']) subprocess.run( ['make', j_flag, c_flag], diff --git a/tests/test_aiohttp.py b/tests/test_aiohttp.py index 514d0177..6ab639c3 100644 --- a/tests/test_aiohttp.py +++ b/tests/test_aiohttp.py @@ -95,7 +95,7 @@ async def on_shutdown(app): async def client(): async with aiohttp.ClientSession() as client: async with client.ws_connect( - 'http://127.0.0.1:{}'.format(port)) as ws: + f'http://127.0.0.1:{port}') as ws: await ws.send_str("hello") async for msg in ws: assert msg.data == "hello" diff --git a/tests/test_base.py b/tests/test_base.py index feac44b8..3703d72c 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -214,9 +214,9 @@ def cb(): for i in range(8): self.loop.call_later(0.06 + 0.01, cb) # 0.06999999999999999 - started = int(round(self.loop.time() * 1000)) + started = round(self.loop.time() * 1000) self.loop.run_forever() - finished = int(round(self.loop.time() * 1000)) + finished = round(self.loop.time() * 1000) self.assertGreaterEqual(finished - started, 69) def test_call_at(self): @@ -770,7 +770,7 @@ def test_loop_call_later_handle_cancelled(self): def test_loop_std_files_cloexec(self): # See https://github.com/MagicStack/uvloop/issues/40 for details. - for fd in {0, 1, 2}: + for fd in (0, 1, 2): flags = fcntl.fcntl(fd, fcntl.F_GETFD) self.assertFalse(flags & fcntl.FD_CLOEXEC) diff --git a/tests/test_context.py b/tests/test_context.py index 03733756..5ba49329 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -61,9 +61,9 @@ def get_buffer(self, sizehint): if self.buffered_ctx is None: self.buffered_ctx = self.cvar.get() elif self.cvar.get() != self.buffered_ctx: - self.data_received_fut.set_exception(ValueError("{} != {}".format( - self.buffered_ctx, self.cvar.get(), - ))) + self.data_received_fut.set_exception( + ValueError(f"{self.buffered_ctx} != {self.cvar.get()}") + ) return bytearray(65536) def buffer_updated(self, nbytes): @@ -72,9 +72,7 @@ def buffer_updated(self, nbytes): self.data_received_fut.set_result(self.cvar.get()) else: self.data_received_fut.set_exception( - ValueError("{} != {}".format( - self.buffered_ctx, self.cvar.get(), - )) + ValueError(f"{self.buffered_ctx} != {self.cvar.get()}") ) @@ -202,16 +200,16 @@ def fut_on_done(fut): for j in range(2): fut = self.loop.create_future() fut.add_done_callback(fut_on_done) - cvar.set('yes{}'.format(j)) + cvar.set(f'yes{j}') self.loop.call_soon(fut.set_result, None) await fut - self.assertEqual(cvar.get(), 'yes{}'.format(j)) + self.assertEqual(cvar.get(), f'yes{j}') for i in range(3): # Test that task passed its context to add_done_callback: - cvar.set('yes{}-{}'.format(i, j)) + cvar.set(f'yes{i}-{j}') await asyncio.sleep(0.001) - self.assertEqual(cvar.get(), 'yes{}-{}'.format(i, j)) + self.assertEqual(cvar.get(), f'yes{i}-{j}') task = self.loop.create_task(main()) self.loop.run_until_complete(task) diff --git a/tests/test_cython.py b/tests/test_cython.py index 5292fba7..785451c9 100644 --- a/tests/test_cython.py +++ b/tests/test_cython.py @@ -13,8 +13,9 @@ def test_cython_coro_is_coroutine(self): coro_fmt = _format_coroutine(coro) self.assertTrue( - coro_fmt.startswith('_test_coroutine_1() done') - or coro_fmt.startswith('_test_coroutine_1() running') + coro_fmt.startswith( + ('_test_coroutine_1() done', '_test_coroutine_1() running') + ) ) self.assertEqual(_test_coroutine_1.__qualname__, '_test_coroutine_1') self.assertEqual(_test_coroutine_1.__name__, '_test_coroutine_1') diff --git a/tests/test_dns.py b/tests/test_dns.py index 2647cc0c..6ec13b0e 100644 --- a/tests/test_dns.py +++ b/tests/test_dns.py @@ -243,7 +243,7 @@ def test_getaddrinfo_close_loop(self): try: # Check that we have internet connection socket.getaddrinfo('example.com', 80) - except socket.error: + except OSError: raise unittest.SkipTest async def run(): diff --git a/tests/test_executors.py b/tests/test_executors.py index c793bb90..65da114c 100644 --- a/tests/test_executors.py +++ b/tests/test_executors.py @@ -18,9 +18,10 @@ def run_pool_test(self, pool_factory): async def run(): pool = pool_factory() with pool: - coros = [] - for i in range(0, 10): - coros.append(self.loop.run_in_executor(pool, fib, i)) + coros = [ + self.loop.run_in_executor(pool, fib, i) + for i in range(0, 10) + ] res = await asyncio.gather(*coros) self.assertEqual(res, fib10) await asyncio.sleep(0.01) diff --git a/tests/test_pipes.py b/tests/test_pipes.py index c2b8a016..ced0e805 100644 --- a/tests/test_pipes.py +++ b/tests/test_pipes.py @@ -1,5 +1,4 @@ import asyncio -import io import os import socket @@ -74,7 +73,7 @@ def test_read_pipe(self): proto = MyReadPipeProto(loop=self.loop) rpipe, wpipe = os.pipe() - pipeobj = io.open(rpipe, 'rb', 1024) + pipeobj = open(rpipe, 'rb', 1024) async def connect(): t, p = await self.loop.connect_read_pipe( @@ -106,7 +105,7 @@ def test_read_pty_output(self): proto = MyReadPipeProto(loop=self.loop) master, slave = os.openpty() - master_read_obj = io.open(master, 'rb', 0) + master_read_obj = open(master, 'rb', 0) async def connect(): t, p = await self.loop.connect_read_pipe( @@ -142,7 +141,7 @@ async def connect(): def test_write_pipe(self): rpipe, wpipe = os.pipe() os.set_blocking(rpipe, False) - pipeobj = io.open(wpipe, 'wb', 1024) + pipeobj = open(wpipe, 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) @@ -185,7 +184,7 @@ def test_write_pipe_disconnect_on_close(self): rsock, wsock = socket.socketpair() rsock.setblocking(False) - pipeobj = io.open(wsock.detach(), 'wb', 1024) + pipeobj = open(wsock.detach(), 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) @@ -207,7 +206,7 @@ def test_write_pty(self): master, slave = os.openpty() os.set_blocking(master, False) - slave_write_obj = io.open(slave, 'wb', 0) + slave_write_obj = open(slave, 'wb', 0) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, slave_write_obj) @@ -250,7 +249,7 @@ def reader(data): def test_write_buffer_full(self): rpipe, wpipe = os.pipe() - pipeobj = io.open(wpipe, 'wb', 1024) + pipeobj = open(wpipe, 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) diff --git a/tests/test_process.py b/tests/test_process.py index bfcbba17..329b2264 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -192,7 +192,7 @@ async def test(): stdout=subprocess.PIPE) pid = proc.pid - expected_result = '{}\n'.format(pid).encode() + expected_result = f'{pid}\n'.encode() out, err = await proc.communicate() self.assertEqual(out, expected_result) diff --git a/tests/test_process_spawning.py b/tests/test_process_spawning.py index 71fe914d..4aab37bd 100644 --- a/tests/test_process_spawning.py +++ b/tests/test_process_spawning.py @@ -100,8 +100,8 @@ def spawn_process(): t.start() t.join(timeout=10.0) if t.is_alive(): - raise Exception('process freeze detected at {}' - .format(iteration)) + raise Exception(f'process freeze detected at {iteration}' + ) return True diff --git a/tests/test_signals.py b/tests/test_signals.py index 7e8ed220..dace02b4 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -297,8 +297,7 @@ def handler_hup(): def test_signals_invalid_signal(self): with self.assertRaisesRegex(RuntimeError, - 'sig {} cannot be caught'.format( - signal.SIGKILL)): + f'sig {signal.SIGKILL} cannot be caught'): self.loop.add_signal_handler(signal.SIGKILL, lambda *a: None) diff --git a/tests/test_sourcecode.py b/tests/test_sourcecode.py index 370ec6ff..51cf51a0 100644 --- a/tests/test_sourcecode.py +++ b/tests/test_sourcecode.py @@ -26,15 +26,14 @@ def test_flake8(self): subprocess.run( [sys.executable, '-m', 'flake8', '--config', config_path], check=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, cwd=os.path.join(edgepath, subdir)) except subprocess.CalledProcessError as ex: output = ex.stdout.decode() output += '\n' output += ex.stderr.decode() raise AssertionError( - 'flake8 validation failed: {}\n{}'.format(ex, output) + f'flake8 validation failed: {ex}\n{output}' ) from None def test_mypy(self): @@ -59,8 +58,7 @@ def test_mypy(self): 'uvloop' ], check=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, cwd=edgepath ) except subprocess.CalledProcessError as ex: @@ -68,5 +66,5 @@ def test_mypy(self): output += '\n' output += ex.stderr.decode() raise AssertionError( - 'mypy validation failed: {}\n{}'.format(ex, output) + f'mypy validation failed: {ex}\n{output}' ) from None diff --git a/tests/test_tcp.py b/tests/test_tcp.py index 8759383d..52bde1fc 100644 --- a/tests/test_tcp.py +++ b/tests/test_tcp.py @@ -1,5 +1,4 @@ import asyncio -import asyncio.sslproto import gc import os import select @@ -46,7 +45,7 @@ def eof_received(self): self.state = 'EOF' def connection_lost(self, exc): - assert self.state in ('CONNECTED', 'EOF'), self.state + assert self.state in {'CONNECTED', 'EOF'}, self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) @@ -124,9 +123,7 @@ async def start_server(): addr = srv_socks[0].getsockname() - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -168,9 +165,7 @@ async def start_server_sock(): self.assertTrue(srv_socks) self.assertTrue(srv.is_serving()) - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -470,9 +465,7 @@ def run(coro): with self.tcp_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) @@ -527,9 +520,7 @@ def run(coro): with self.tcp_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) @@ -626,9 +617,7 @@ async def start_server(): addr = srv_socks[0].getsockname() - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -1335,9 +1324,7 @@ async def start_server(): addr = srv_socks[0].getsockname() - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -1431,9 +1418,7 @@ def run(coro): with self.tcp_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) @@ -1634,11 +1619,10 @@ def test_ssl_connect_accepted_socket(self): if hasattr(ssl, 'PROTOCOL_TLS_SERVER'): server_proto = ssl.PROTOCOL_TLS_SERVER client_proto = ssl.PROTOCOL_TLS_CLIENT + elif hasattr(ssl, 'PROTOCOL_TLS'): + client_proto = server_proto = ssl.PROTOCOL_TLS else: - if hasattr(ssl, 'PROTOCOL_TLS'): - client_proto = server_proto = ssl.PROTOCOL_TLS - else: - client_proto = server_proto = ssl.PROTOCOL_SSLv23 + client_proto = server_proto = ssl.PROTOCOL_SSLv23 server_context = ssl.SSLContext(server_proto) server_context.load_cert_chain(self.ONLYCERT, self.ONLYKEY) @@ -2205,9 +2189,7 @@ async def start_server(): addr = srv_socks[0].getsockname() - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -2327,9 +2309,7 @@ def run(coro): with self.tcp_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete( asyncio.gather(*tasks)) @@ -2420,9 +2400,7 @@ async def start_server(): addr = srv_socks[0].getsockname() - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(addr)) + tasks = [test_client(addr) for _ in range(TOTAL_CNT)] await asyncio.wait_for( asyncio.gather(*tasks), @@ -2492,9 +2470,7 @@ def run(coro): with self.tcp_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete( asyncio.gather(*tasks)) @@ -2810,7 +2786,7 @@ async def test(): except AssertionError as e: self.assertEqual(str(e), 'ResourceWarning not triggered') else: - self.fail('Unexpected ResourceWarning: {}'.format(cm.warning)) + self.fail(f'Unexpected ResourceWarning: {cm.warning}') def test_handshake_timeout_handler_leak(self): if self.implementation == 'asyncio': diff --git a/tests/test_unix.py b/tests/test_unix.py index 0d670e39..52a97e6d 100644 --- a/tests/test_unix.py +++ b/tests/test_unix.py @@ -71,9 +71,7 @@ async def start_server(): self.assertTrue(srv_socks) self.assertTrue(srv.is_serving()) - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(sock_name)) + tasks = [test_client(sock_name) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -123,9 +121,7 @@ async def start_server_sock(start_server, is_unix_api=True): self.assertTrue(srv_socks) self.assertTrue(srv.is_serving()) - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(sock_name)) + tasks = [test_client(sock_name) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -181,8 +177,7 @@ def test_create_unix_server_2(self): f.write('x') with self.assertRaisesRegex( - OSError, "Address '{}' is already in use".format( - sock_name)): + OSError, f"Address '{sock_name}' is already in use"): self.loop.run_until_complete( self.loop.create_unix_server(object, sock_name)) @@ -282,9 +277,7 @@ def run(coro): with self.unix_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) @@ -343,9 +336,7 @@ def run(coro): with self.unix_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) @@ -610,9 +601,7 @@ async def start_server(): **extras) try: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(test_client(sock_name)) + tasks = [test_client(sock_name) for _ in range(TOTAL_CNT)] await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) @@ -686,9 +675,7 @@ def run(coro): with self.unix_server(server, max_clients=TOTAL_CNT, backlog=TOTAL_CNT) as srv: - tasks = [] - for _ in range(TOTAL_CNT): - tasks.append(coro(srv.addr)) + tasks = [coro(srv.addr) for _ in range(TOTAL_CNT)] self.loop.run_until_complete(asyncio.gather(*tasks)) diff --git a/uvloop/__init__.py b/uvloop/__init__.py index 638b874c..1b542fb4 100644 --- a/uvloop/__init__.py +++ b/uvloop/__init__.py @@ -58,7 +58,7 @@ async def wrapper(): if not __asyncio.iscoroutine(main): raise ValueError( - "a coroutine was expected, got {!r}".format(main) + f"a coroutine was expected, got {main!r}" ) loop = loop_factory() @@ -161,7 +161,7 @@ def install() -> None: class EventLoopPolicy( # This is to avoid a mypy error about AbstractEventLoopPolicy - getattr(__asyncio, 'AbstractEventLoopPolicy') # type: ignore[misc] + __asyncio.AbstractEventLoopPolicy # type: ignore[misc] ): """Event loop policy for uvloop. @@ -204,8 +204,8 @@ def get_event_loop(self) -> _AbstractEventLoop: """ if self._local._loop is None: raise RuntimeError( - 'There is no current event loop in thread %r.' - % threading.current_thread().name + 'There is no current event loop in ' + f'thread {threading.current_thread().name!r}.' ) return self._local._loop diff --git a/uvloop/_testbase.py b/uvloop/_testbase.py index e620e158..137704a2 100644 --- a/uvloop/_testbase.py +++ b/uvloop/_testbase.py @@ -2,7 +2,6 @@ import asyncio -import asyncio.events import collections import contextlib import gc @@ -22,6 +21,8 @@ class MockPattern(str): + __slots__ = () + def __eq__(self, other): return bool(re.search(str(self), other, re.S)) @@ -34,8 +35,7 @@ def __init__(self, name): def __setitem__(self, key, value): if key in self.data: - raise RuntimeError('duplicate test {}.{}'.format( - self.name, key)) + raise RuntimeError(f'duplicate test {self.name}.{key}') super().__setitem__(key, value) @@ -52,9 +52,8 @@ def __new__(mcls, name, bases, dct): for base in bases: if hasattr(base, test_name): raise RuntimeError( - 'duplicate test {}.{} (also defined in {} ' - 'parent class)'.format( - name, test_name, base.__name__)) + f'duplicate test {name}.{test_name} (also defined in ' + f'{base.__name__} parent class)') return super().__new__(mcls, name, bases, dict(dct)) @@ -141,14 +140,14 @@ def tearDown(self): handle_name=h_name): self.assertEqual( h_cnt, 0, - 'alive {} after test'.format(h_name)) + f'alive {h_name} after test') for h_name, h_cnt in self.loop._debug_handles_total.items(): with self.subTest('Total/closed handles', handle_name=h_name): self.assertEqual( h_cnt, self.loop._debug_handles_closed[h_name], - 'total != closed for {}'.format(h_name)) + f'total != closed for {h_name}') asyncio.set_event_loop(None) asyncio.set_event_loop_policy(None) @@ -259,7 +258,7 @@ def find_free_port(start_from=50000): with sock: try: sock.bind(('', port)) - except socket.error: + except OSError: continue else: return port @@ -388,7 +387,7 @@ def __getattr__(self, name): return getattr(self.__sock, name) def __repr__(self): - return '<{} {!r}>'.format(type(self).__name__, self.__sock) + return f'<{type(self).__name__} {self.__sock!r}>' class SocketThread(threading.Thread): diff --git a/uvloop/loop.pyi b/uvloop/loop.pyi index 9c8c4623..017f3a7b 100644 --- a/uvloop/loop.pyi +++ b/uvloop/loop.pyi @@ -1,41 +1,35 @@ import asyncio import ssl -import sys from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket from typing import ( IO, Any, Awaitable, Callable, - Dict, Generator, - List, - Optional, Sequence, - Tuple, TypeVar, - Union, overload, ) _T = TypeVar('_T') -_Context = Dict[str, Any] +_Context = dict[str, Any] _ExceptionHandler = Callable[[asyncio.AbstractEventLoop, _Context], Any] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | ssl.SSLContext | None _ProtocolT = TypeVar("_ProtocolT", bound=asyncio.BaseProtocol) class Loop: def call_soon( - self, callback: Callable[..., Any], *args: Any, context: Optional[Any] = ... + self, callback: Callable[..., Any], *args: Any, context: Any | None = ... ) -> asyncio.Handle: ... def call_soon_threadsafe( - self, callback: Callable[..., Any], *args: Any, context: Optional[Any] = ... + self, callback: Callable[..., Any], *args: Any, context: Any | None = ... ) -> asyncio.Handle: ... def call_later( - self, delay: float, callback: Callable[..., Any], *args: Any, context: Optional[Any] = ... + self, delay: float, callback: Callable[..., Any], *args: Any, context: Any | None = ... ) -> asyncio.TimerHandle: ... def call_at( - self, when: float, callback: Callable[..., Any], *args: Any, context: Optional[Any] = ... + self, when: float, callback: Callable[..., Any], *args: Any, context: Any | None = ... ) -> asyncio.TimerHandle: ... def time(self) -> float: ... def stop(self) -> None: ... @@ -48,52 +42,44 @@ class Loop: def create_future(self) -> asyncio.Future[Any]: ... def create_task( self, - coro: Union[Awaitable[_T], Generator[Any, None, _T]], + coro: Awaitable[_T] | Generator[Any, None, _T], *, - name: Optional[str] = ..., + name: str | None = ..., ) -> asyncio.Task[_T]: ... def set_task_factory( self, - factory: Optional[ - Callable[[asyncio.AbstractEventLoop, Generator[Any, None, _T]], asyncio.Future[_T]] - ], + factory: Callable[[asyncio.AbstractEventLoop, Generator[Any, None, _T]], asyncio.Future[_T]] | None, ) -> None: ... def get_task_factory( self, - ) -> Optional[ - Callable[[asyncio.AbstractEventLoop, Generator[Any, None, _T]], asyncio.Future[_T]] - ]: ... + ) -> Callable[[asyncio.AbstractEventLoop, Generator[Any, None, _T]], asyncio.Future[_T]] | None: ... @overload def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... @overload def run_until_complete(self, future: Awaitable[_T]) -> _T: ... async def getaddrinfo( self, - host: Optional[Union[str, bytes]], - port: Optional[Union[str, bytes, int]], + host: str | bytes | None, + port: str | bytes | int | None, *, family: int = ..., type: int = ..., proto: int = ..., flags: int = ..., - ) -> List[ - Tuple[ + ) -> list[ + tuple[ AddressFamily, SocketKind, int, str, - Union[Tuple[str, int], Tuple[str, int, int, int]], + tuple[str, int] | tuple[str, int, int, int], ] ]: ... async def getnameinfo( self, - sockaddr: Union[ - Tuple[str, int], - Tuple[str, int, int], - Tuple[str, int, int, int] - ], + sockaddr: tuple[str, int] | tuple[str, int, int] | tuple[str, int, int, int], flags: int = ..., - ) -> Tuple[str, str]: ... + ) -> tuple[str, str]: ... async def start_tls( self, transport: asyncio.BaseTransport, @@ -101,15 +87,15 @@ class Loop: sslcontext: ssl.SSLContext, *, server_side: bool = ..., - server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> asyncio.BaseTransport: ... @overload async def create_server( self, protocol_factory: asyncio.events._ProtocolFactory, - host: Optional[Union[str, Sequence[str]]] = ..., + host: str | Sequence[str] | None = ..., port: int = ..., *, family: int = ..., @@ -117,10 +103,10 @@ class Loop: sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> asyncio.AbstractServer: ... @overload @@ -135,10 +121,10 @@ class Loop: sock: socket = ..., backlog: int = ..., ssl: _SSLContext = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> asyncio.AbstractServer: ... @overload @@ -153,10 +139,10 @@ class Loop: proto: int = ..., flags: int = ..., sock: None = ..., - local_addr: Optional[Tuple[str, int]] = ..., - server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + local_addr: tuple[str, int] | None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[asyncio.BaseProtocol, _ProtocolT]: ... @overload async def create_connection( @@ -171,36 +157,36 @@ class Loop: flags: int = ..., sock: socket, local_addr: None = ..., - server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[asyncio.BaseProtocol, _ProtocolT]: ... async def create_unix_server( self, protocol_factory: asyncio.events._ProtocolFactory, - path: Optional[str] = ..., + path: str | None = ..., *, backlog: int = ..., - sock: Optional[socket] = ..., + sock: socket | None = ..., ssl: _SSLContext = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> asyncio.AbstractServer: ... async def create_unix_connection( self, protocol_factory: Callable[[], _ProtocolT], - path: Optional[str] = ..., + path: str | None = ..., *, ssl: _SSLContext = ..., - sock: Optional[socket] = ..., - server_hostname: Optional[str] = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + sock: socket | None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[asyncio.BaseProtocol, _ProtocolT]: ... def default_exception_handler(self, context: _Context) -> None: ... - def get_exception_handler(self) -> Optional[_ExceptionHandler]: ... - def set_exception_handler(self, handler: Optional[_ExceptionHandler]) -> None: ... + def get_exception_handler(self) -> _ExceptionHandler | None: ... + def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ... def call_exception_handler(self, context: _Context) -> None: ... def add_reader(self, fd: Any, callback: Callable[..., Any], *args: Any) -> None: ... def remove_reader(self, fd: Any) -> None: ... @@ -209,7 +195,7 @@ class Loop: async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... async def sock_sendall(self, sock: socket, data: bytes) -> None: ... - async def sock_accept(self, sock: socket) -> Tuple[socket, _RetAddress]: ... + async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... async def sock_connect(self, sock: socket, address: _Address) -> None: ... async def sock_recvfrom(self, sock: socket, bufsize: int) -> bytes: ... async def sock_recvfrom_into(self, sock: socket, buf: bytearray, nbytes: int = ...) -> int: ... @@ -220,8 +206,8 @@ class Loop: sock: socket, *, ssl: _SSLContext = ..., - ssl_handshake_timeout: Optional[float] = ..., - ssl_shutdown_timeout: Optional[float] = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[asyncio.BaseProtocol, _ProtocolT]: ... async def run_in_executor( self, executor: Any, func: Callable[..., _T], *args: Any @@ -230,7 +216,7 @@ class Loop: async def subprocess_shell( self, protocol_factory: Callable[[], _ProtocolT], - cmd: Union[bytes, str], + cmd: bytes | str, *, stdin: Any = ..., stdout: Any = ..., @@ -259,21 +245,21 @@ class Loop: async def create_datagram_endpoint( self, protocol_factory: Callable[[], _ProtocolT], - local_addr: Optional[Tuple[str, int]] = ..., - remote_addr: Optional[Tuple[str, int]] = ..., + local_addr: tuple[str, int] | None = ..., + remote_addr: tuple[str, int] | None = ..., *, family: int = ..., proto: int = ..., flags: int = ..., - reuse_address: Optional[bool] = ..., - reuse_port: Optional[bool] = ..., - allow_broadcast: Optional[bool] = ..., - sock: Optional[socket] = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + allow_broadcast: bool | None = ..., + sock: socket | None = ..., ) -> tuple[asyncio.BaseProtocol, _ProtocolT]: ... async def shutdown_asyncgens(self) -> None: ... async def shutdown_default_executor( self, - timeout: Optional[float] = ..., + timeout: float | None = ..., ) -> None: ... # Loop doesn't implement these, but since they are marked as abstract in typeshed, # we have to put them in so mypy thinks the base methods are overridden @@ -282,7 +268,7 @@ class Loop: transport: asyncio.BaseTransport, file: IO[bytes], offset: int = ..., - count: Optional[int] = ..., + count: int | None = ..., *, fallback: bool = ..., ) -> int: ... @@ -291,7 +277,7 @@ class Loop: sock: socket, file: IO[bytes], offset: int = ..., - count: Optional[int] = ..., + count: int | None = ..., *, fallback: bool = ... ) -> int: ...