Skip to content

Commit 6370f34

Browse files
authored
bpo-32262: Fix codestyle; use f-strings formatting where necessary. (python#4775)
1 parent c4d9df5 commit 6370f34

24 files changed

+332
-348
lines changed

Lib/asyncio/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""The asyncio package, tracking PEP 3156."""
22

3+
# flake8: noqa
4+
35
import sys
46

57
# This relies on each of the submodules having an __all__ variable.

Lib/asyncio/base_events.py

Lines changed: 60 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
from .log import logger
3737

3838

39-
__all__ = ['BaseEventLoop']
39+
__all__ = 'BaseEventLoop',
4040

4141

4242
# 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,
173173

174174
def _run_until_complete_cb(fut):
175175
exc = 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.
180179
return
@@ -190,7 +189,7 @@ def __init__(self, loop, sockets):
190189
self._waiters = []
191190

192191
def __repr__(self):
193-
return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
192+
return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
194193

195194
def _attach(self):
196195
assert self.sockets is not None
@@ -262,9 +261,10 @@ def __init__(self):
262261
self._asyncgens_shutdown_called = False
263262

264263
def __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+
)
268268

269269
def create_future(self):
270270
"""Create a Future object attached to the loop."""
@@ -362,8 +362,8 @@ def _asyncgen_finalizer_hook(self, agen):
362362
def _asyncgen_firstiter_hook(self, agen):
363363
if self._asyncgens_shutdown_called:
364364
warnings.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",
367367
ResourceWarning, source=self)
368368

369369
self._asyncgens.add(agen)
@@ -388,8 +388,8 @@ async def shutdown_asyncgens(self):
388388
for result, agen in zip(results, closing_agens):
389389
if isinstance(result, Exception):
390390
self.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):
495495

496496
def __del__(self):
497497
if not self.is_closed():
498-
warnings.warn("unclosed event loop %r" % self, ResourceWarning,
498+
warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
499499
source=self)
500500
if not self.is_running():
501501
self.close()
@@ -573,12 +573,11 @@ def _check_callback(self, callback, method):
573573
if (coroutines.iscoroutine(callback) or
574574
coroutines.iscoroutinefunction(callback)):
575575
raise TypeError(
576-
"coroutines cannot be used with {}()".format(method))
576+
f"coroutines cannot be used with {method}()")
577577
if not callable(callback):
578578
raise 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}')
582581

583582
def _call_soon(self, callback, args):
584583
handle = events.Handle(callback, args, self)
@@ -630,24 +629,23 @@ def set_default_executor(self, executor):
630629
self._default_executor = executor
631630

632631
def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
633-
msg = ["%s:%r" % (host, port)]
632+
msg = [f"{host}:{port!r}"]
634633
if family:
635-
msg.append('family=%r' % family)
634+
msg.append(f'family={family!r}' % family)
636635
if type:
637-
msg.append('type=%r' % type)
636+
msg.append(f'type={type!r}')
638637
if proto:
639-
msg.append('proto=%r' % proto)
638+
msg.append(f'proto={proto!r}')
640639
if flags:
641-
msg.append('flags=%r' % flags)
640+
msg.append(f'flags={flags!r}')
642641
msg = ', '.join(msg)
643642
logger.debug('Get address info %s', msg)
644643

645644
t0 = self.time()
646645
addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
647646
dt = self.time() - t0
648647

649-
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}'
651649
if dt >= self.slow_callback_duration:
652650
logger.info(msg)
653651
else:
@@ -738,11 +736,12 @@ async def create_connection(self, protocol_factory, host=None, port=None,
738736
sock.bind(laddr)
739737
break
740738
except 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)
746745
exceptions.append(exc)
747746
else:
748747
sock.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.
788787
raise ValueError(
789-
'A Stream Socket was expected, got {!r}'.format(sock))
788+
f'A Stream Socket was expected, got {sock!r}')
790789

791790
transport, protocol = await self._create_connection_transport(
792791
sock, protocol_factory, ssl, server_hostname)
@@ -830,7 +829,7 @@ async def create_datagram_endpoint(self, protocol_factory,
830829
if sock is not None:
831830
if not _is_dgram_socket(sock):
832831
raise ValueError(
833-
'A UDP Socket was expected, got {!r}'.format(sock))
832+
f'A UDP Socket was expected, got {sock!r}')
834833
if (local_addr or remote_addr or
835834
family or proto or flags or
836835
reuse_address or reuse_port or allow_broadcast):
@@ -839,11 +838,10 @@ async def create_datagram_endpoint(self, protocol_factory,
839838
family=family, proto=proto, flags=flags,
840839
reuse_address=reuse_address, reuse_port=reuse_port,
841840
allow_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)
844842
raise 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})')
847845
sock.setblocking(False)
848846
r_addr = None
849847
else:
@@ -953,7 +951,7 @@ async def _create_server_getaddrinfo(self, host, port, family, flags):
953951
type=socket.SOCK_STREAM,
954952
flags=flags, loop=self)
955953
if not infos:
956-
raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
954+
raise OSError(f'getaddrinfo({host!r}) returned empty list')
957955
return infos
958956

959957
async 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,
967965
reuse_port=None):
968966
"""Create a TCP server.
969967
970-
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.
972970
973971
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,
10461044
if sock is None:
10471045
raise ValueError('Neither host/port nor sock were specified')
10481046
if 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}')
10511048
sockets = [sock]
10521049

10531050
server = Server(self, sockets)
@@ -1070,8 +1067,7 @@ async def connect_accepted_socket(self, protocol_factory, sock,
10701067
returns a (transport, protocol) pair.
10711068
"""
10721069
if 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}')
10751071

10761072
transport, protocol = await self._create_connection_transport(
10771073
sock, protocol_factory, ssl, '', server_side=True)
@@ -1117,14 +1113,14 @@ async def connect_write_pipe(self, protocol_factory, pipe):
11171113
def _log_subprocess(self, msg, stdin, stdout, stderr):
11181114
info = [msg]
11191115
if stdin is not None:
1120-
info.append('stdin=%s' % _format_pipe(stdin))
1116+
info.append(f'stdin={_format_pipe(stdin)}')
11211117
if 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)}')
11231119
else:
11241120
if stdout is not None:
1125-
info.append('stdout=%s' % _format_pipe(stdout))
1121+
info.append(f'stdout={_format_pipe(stdout)}')
11261122
if stderr is not None:
1127-
info.append('stderr=%s' % _format_pipe(stderr))
1123+
info.append(f'stderr={_format_pipe(stderr)}')
11281124
logger.debug(' '.join(info))
11291125

11301126
async def subprocess_shell(self, protocol_factory, cmd, *,
@@ -1167,14 +1163,14 @@ async def subprocess_exec(self, protocol_factory, program, *args,
11671163
popen_args = (program,) + args
11681164
for arg in popen_args:
11691165
if 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__}")
11731169
protocol = protocol_factory()
11741170
if 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}'
11781174
self._log_subprocess(debug_log, stdin, stdout, stderr)
11791175
transport = await self._make_subprocess_transport(
11801176
protocol, popen_args, False, stdin, stdout, stderr,
@@ -1201,8 +1197,8 @@ def set_exception_handler(self, handler):
12011197
documentation for details about context).
12021198
"""
12031199
if 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}')
12061202
self._exception_handler = handler
12071203

12081204
def default_exception_handler(self, context):
@@ -1230,10 +1226,11 @@ def default_exception_handler(self, context):
12301226
else:
12311227
exc_info = False
12321228

1233-
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
12371234

12381235
log_lines = [message]
12391236
for key in sorted(context):
@@ -1250,7 +1247,7 @@ def default_exception_handler(self, context):
12501247
value += tb.rstrip()
12511248
else:
12521249
value = repr(value)
1253-
log_lines.append('{}: {}'.format(key, value))
1250+
log_lines.append(f'{key}: {value}')
12541251

12551252
logger.error('\n'.join(log_lines), exc_info=exc_info)
12561253

@@ -1438,18 +1435,19 @@ def _set_coroutine_wrapper(self, enabled):
14381435
if enabled:
14391436
if current_wrapper not in (None, wrapper):
14401437
warnings.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)
14441442
else:
14451443
set_wrapper(wrapper)
14461444
self._coroutine_wrapper_set = True
14471445
else:
14481446
if current_wrapper not in (None, wrapper):
14491447
warnings.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)
14531451
else:
14541452
set_wrapper(None)
14551453
self._coroutine_wrapper_set = False

Lib/asyncio/base_futures.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__all__ = []
1+
__all__ = ()
22

33
import concurrent.futures._base
44
import reprlib
@@ -48,7 +48,7 @@ def format_cb(callback):
4848
cb = '{}, <{} more>, {}'.format(format_cb(cb[0]),
4949
size - 2,
5050
format_cb(cb[-1]))
51-
return 'cb=[%s]' % cb
51+
return f'cb=[{cb}]'
5252

5353

5454
def _future_repr_info(future):
@@ -57,15 +57,15 @@ def _future_repr_info(future):
5757
info = [future._state.lower()]
5858
if future._state == _FINISHED:
5959
if future._exception is not None:
60-
info.append('exception={!r}'.format(future._exception))
60+
info.append(f'exception={future._exception!r}')
6161
else:
6262
# use reprlib to limit the length of the output, especially
6363
# for very long strings
6464
result = reprlib.repr(future._result)
65-
info.append('result={}'.format(result))
65+
info.append(f'result={result}')
6666
if future._callbacks:
6767
info.append(_format_callbacks(future._callbacks))
6868
if future._source_traceback:
6969
frame = future._source_traceback[-1]
70-
info.append('created at %s:%s' % (frame[0], frame[1]))
70+
info.append(f'created at {frame[0]}:{frame[1]}')
7171
return info

0 commit comments

Comments
 (0)