bpo-32262: Fix codestyle; use f-strings formatting where necessary. (… · python/cpython@6370f34
@@ -36,7 +36,7 @@
3636from .log import logger
3737383839-__all__ = ['BaseEventLoop']
39+__all__ = 'BaseEventLoop',
404041414242# Minimum number of _scheduled timer handles before cleanup of
@@ -173,8 +173,7 @@ def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
173173174174def _run_until_complete_cb(fut):
175175exc = fut._exception
176-if (isinstance(exc, BaseException)
177-and not isinstance(exc, Exception)):
176+if isinstance(exc, BaseException) and not isinstance(exc, Exception):
178177# Issue #22429: run_forever() already finished, no need to
179178# stop it.
180179return
@@ -190,7 +189,7 @@ def __init__(self, loop, sockets):
190189self._waiters = []
191190192191def __repr__(self):
193-return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
192+return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
194193195194def _attach(self):
196195assert self.sockets is not None
@@ -262,9 +261,10 @@ def __init__(self):
262261self._asyncgens_shutdown_called = False
263262264263def __repr__(self):
265-return ('<%s running=%s closed=%s debug=%s>'
266-% (self.__class__.__name__, self.is_running(),
267-self.is_closed(), self.get_debug()))
264+return (
265+f'<{self.__class__.__name__} running={self.is_running()} '
266+f'closed={self.is_closed()} debug={self.get_debug()}>'
267+ )
268268269269def create_future(self):
270270"""Create a Future object attached to the loop."""
@@ -362,8 +362,8 @@ def _asyncgen_finalizer_hook(self, agen):
362362def _asyncgen_firstiter_hook(self, agen):
363363if self._asyncgens_shutdown_called:
364364warnings.warn(
365-"asynchronous generator {!r} was scheduled after "
366-"loop.shutdown_asyncgens() call".format(agen),
365+f"asynchronous generator {agen!r} was scheduled after "
366+f"loop.shutdown_asyncgens() call",
367367ResourceWarning, source=self)
368368369369self._asyncgens.add(agen)
@@ -388,8 +388,8 @@ async def shutdown_asyncgens(self):
388388for result, agen in zip(results, closing_agens):
389389if isinstance(result, Exception):
390390self.call_exception_handler({
391-'message': 'an error occurred during closing of '
392-'asynchronous generator {!r}'.format(agen),
391+'message': f'an error occurred during closing of '
392+f'asynchronous generator {agen!r}',
393393'exception': result,
394394'asyncgen': agen
395395 })
@@ -495,7 +495,7 @@ def is_closed(self):
495495496496def __del__(self):
497497if not self.is_closed():
498-warnings.warn("unclosed event loop %r" % self, ResourceWarning,
498+warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
499499source=self)
500500if not self.is_running():
501501self.close()
@@ -573,12 +573,11 @@ def _check_callback(self, callback, method):
573573if (coroutines.iscoroutine(callback) or
574574coroutines.iscoroutinefunction(callback)):
575575raise TypeError(
576-"coroutines cannot be used with {}()".format(method))
576+f"coroutines cannot be used with {method}()")
577577if not callable(callback):
578578raise TypeError(
579-'a callable object was expected by {}(), got {!r}'.format(
580-method, callback))
581-579+f'a callable object was expected by {method}(), '
580+f'got {callback!r}')
582581583582def _call_soon(self, callback, args):
584583handle = events.Handle(callback, args, self)
@@ -630,24 +629,23 @@ def set_default_executor(self, executor):
630629self._default_executor = executor
631630632631def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
633-msg = ["%s:%r" % (host, port)]
632+msg = [f"{host}:{port!r}"]
634633if family:
635-msg.append('family=%r' % family)
634+msg.append(f'family={family!r}' % family)
636635if type:
637-msg.append('type=%r' % type)
636+msg.append(f'type={type!r}')
638637if proto:
639-msg.append('proto=%r' % proto)
638+msg.append(f'proto={proto!r}')
640639if flags:
641-msg.append('flags=%r' % flags)
640+msg.append(f'flags={flags!r}')
642641msg = ', '.join(msg)
643642logger.debug('Get address info %s', msg)
644643645644t0 = self.time()
646645addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
647646dt = self.time() - t0
648647649-msg = ('Getting address info %s took %.3f ms: %r'
650-% (msg, dt * 1e3, addrinfo))
648+msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
651649if dt >= self.slow_callback_duration:
652650logger.info(msg)
653651else:
@@ -738,11 +736,12 @@ async def create_connection(self, protocol_factory, host=None, port=None,
738736sock.bind(laddr)
739737break
740738except OSError as exc:
741-exc = OSError(
742-exc.errno, 'error while '
743-'attempting to bind on address '
744-'{!r}: {}'.format(
745-laddr, exc.strerror.lower()))
739+msg = (
740+f'error while attempting to bind on '
741+f'address {laddr!r}: '
742+f'{exc.strerror.lower()}'
743+ )
744+exc = OSError(exc.errno, msg)
746745exceptions.append(exc)
747746else:
748747sock.close()
@@ -786,7 +785,7 @@ async def create_connection(self, protocol_factory, host=None, port=None,
786785# Disallowing AF_UNIX in this method, breaks backwards
787786# compatibility.
788787raise ValueError(
789-'A Stream Socket was expected, got {!r}'.format(sock))
788+f'A Stream Socket was expected, got {sock!r}')
790789791790transport, protocol = await self._create_connection_transport(
792791sock, protocol_factory, ssl, server_hostname)
@@ -830,7 +829,7 @@ async def create_datagram_endpoint(self, protocol_factory,
830829if sock is not None:
831830if not _is_dgram_socket(sock):
832831raise ValueError(
833-'A UDP Socket was expected, got {!r}'.format(sock))
832+f'A UDP Socket was expected, got {sock!r}')
834833if (local_addr or remote_addr or
835834family or proto or flags or
836835reuse_address or reuse_port or allow_broadcast):
@@ -839,11 +838,10 @@ async def create_datagram_endpoint(self, protocol_factory,
839838family=family, proto=proto, flags=flags,
840839reuse_address=reuse_address, reuse_port=reuse_port,
841840allow_broadcast=allow_broadcast)
842-problems = ', '.join(
843-'{}={}'.format(k, v) for k, v in opts.items() if v)
841+problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
844842raise ValueError(
845-'socket modifier keyword arguments can not be used '
846-'when sock is specified. ({})'.format(problems))
843+f'socket modifier keyword arguments can not be used '
844+f'when sock is specified. ({problems})')
847845sock.setblocking(False)
848846r_addr = None
849847else:
@@ -953,7 +951,7 @@ async def _create_server_getaddrinfo(self, host, port, family, flags):
953951type=socket.SOCK_STREAM,
954952flags=flags, loop=self)
955953if not infos:
956-raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
954+raise OSError(f'getaddrinfo({host!r}) returned empty list')
957955return infos
958956959957async def create_server(self, protocol_factory, host=None, port=None,
@@ -967,8 +965,8 @@ async def create_server(self, protocol_factory, host=None, port=None,
967965reuse_port=None):
968966"""Create a TCP server.
969967970- The host parameter can be a string, in that case the TCP server is bound
971- to host and port.
968+ The host parameter can be a string, in that case the TCP server is
969+ bound to host and port.
972970973971 The host parameter can also be a sequence of strings and in that case
974972 the TCP server is bound to all hosts of the sequence. If a host
@@ -1046,8 +1044,7 @@ async def create_server(self, protocol_factory, host=None, port=None,
10461044if sock is None:
10471045raise ValueError('Neither host/port nor sock were specified')
10481046if not _is_stream_socket(sock):
1049-raise ValueError(
1050-'A Stream Socket was expected, got {!r}'.format(sock))
1047+raise ValueError(f'A Stream Socket was expected, got {sock!r}')
10511048sockets = [sock]
1052104910531050server = Server(self, sockets)
@@ -1070,8 +1067,7 @@ async def connect_accepted_socket(self, protocol_factory, sock,
10701067 returns a (transport, protocol) pair.
10711068 """
10721069if not _is_stream_socket(sock):
1073-raise ValueError(
1074-'A Stream Socket was expected, got {!r}'.format(sock))
1070+raise ValueError(f'A Stream Socket was expected, got {sock!r}')
1075107110761072transport, protocol = await self._create_connection_transport(
10771073sock, protocol_factory, ssl, '', server_side=True)
@@ -1117,14 +1113,14 @@ async def connect_write_pipe(self, protocol_factory, pipe):
11171113def _log_subprocess(self, msg, stdin, stdout, stderr):
11181114info = [msg]
11191115if stdin is not None:
1120-info.append('stdin=%s' % _format_pipe(stdin))
1116+info.append(f'stdin={_format_pipe(stdin)}')
11211117if stdout is not None and stderr == subprocess.STDOUT:
1122-info.append('stdout=stderr=%s' % _format_pipe(stdout))
1118+info.append(f'stdout=stderr={_format_pipe(stdout)}')
11231119else:
11241120if stdout is not None:
1125-info.append('stdout=%s' % _format_pipe(stdout))
1121+info.append(f'stdout={_format_pipe(stdout)}')
11261122if stderr is not None:
1127-info.append('stderr=%s' % _format_pipe(stderr))
1123+info.append(f'stderr={_format_pipe(stderr)}')
11281124logger.debug(' '.join(info))
1129112511301126async def subprocess_shell(self, protocol_factory, cmd, *,
@@ -1167,14 +1163,14 @@ async def subprocess_exec(self, protocol_factory, program, *args,
11671163popen_args = (program,) + args
11681164for arg in popen_args:
11691165if not isinstance(arg, (str, bytes)):
1170-raise TypeError("program arguments must be "
1171- "a bytes or text string, not %s"
1172- % type(arg).__name__)
1166+raise TypeError(
1167+f"program arguments must be a bytes or text string, "
1168+f"not {type(arg).__name__}")
11731169protocol = protocol_factory()
11741170if self._debug:
11751171# don't log parameters: they may contain sensitive information
11761172# (password) and may be too long
1177-debug_log = 'execute program %r' % program
1173+debug_log = f'execute program {program!r}'
11781174self._log_subprocess(debug_log, stdin, stdout, stderr)
11791175transport = await self._make_subprocess_transport(
11801176protocol, popen_args, False, stdin, stdout, stderr,
@@ -1201,8 +1197,8 @@ def set_exception_handler(self, handler):
12011197 documentation for details about context).
12021198 """
12031199if handler is not None and not callable(handler):
1204-raise TypeError('A callable object or None is expected, '
1205-'got {!r}'.format(handler))
1200+raise TypeError(f'A callable object or None is expected, '
1201+f'got {handler!r}')
12061202self._exception_handler = handler
1207120312081204def default_exception_handler(self, context):
@@ -1230,10 +1226,11 @@ def default_exception_handler(self, context):
12301226else:
12311227exc_info = False
123212281233-if ('source_traceback' not in context
1234-and self._current_handle is not None
1235-and self._current_handle._source_traceback):
1236-context['handle_traceback'] = self._current_handle._source_traceback
1229+if ('source_traceback' not in context and
1230+self._current_handle is not None and
1231+self._current_handle._source_traceback):
1232+context['handle_traceback'] = \
1233+self._current_handle._source_traceback
1237123412381235log_lines = [message]
12391236for key in sorted(context):
@@ -1250,7 +1247,7 @@ def default_exception_handler(self, context):
12501247value += tb.rstrip()
12511248else:
12521249value = repr(value)
1253-log_lines.append('{}: {}'.format(key, value))
1250+log_lines.append(f'{key}: {value}')
1254125112551252logger.error('\n'.join(log_lines), exc_info=exc_info)
12561253@@ -1438,18 +1435,19 @@ def _set_coroutine_wrapper(self, enabled):
14381435if enabled:
14391436if current_wrapper not in (None, wrapper):
14401437warnings.warn(
1441-"loop.set_debug(True): cannot set debug coroutine "
1442-"wrapper; another wrapper is already set %r" %
1443-current_wrapper, RuntimeWarning)
1438+f"loop.set_debug(True): cannot set debug coroutine "
1439+f"wrapper; another wrapper is already set "
1440+f"{current_wrapper!r}",
1441+RuntimeWarning)
14441442else:
14451443set_wrapper(wrapper)
14461444self._coroutine_wrapper_set = True
14471445else:
14481446if current_wrapper not in (None, wrapper):
14491447warnings.warn(
1450-"loop.set_debug(False): cannot unset debug coroutine "
1451-"wrapper; another wrapper was set %r" %
1452-current_wrapper, RuntimeWarning)
1448+f"loop.set_debug(False): cannot unset debug coroutine "
1449+f"wrapper; another wrapper was set {current_wrapper!r}",
1450+RuntimeWarning)
14531451else:
14541452set_wrapper(None)
14551453self._coroutine_wrapper_set = False