bpo-32262: Fix codestyle; use f-strings formatting where necessary. (#4775)

This commit is contained in:
Yury Selivanov 2017-12-10 18:36:12 -05:00 committed by GitHub
parent c4d9df5fd7
commit 6370f345e1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 332 additions and 348 deletions

View file

@ -1,5 +1,7 @@
"""The asyncio package, tracking PEP 3156.""" """The asyncio package, tracking PEP 3156."""
# flake8: noqa
import sys import sys
# This relies on each of the submodules having an __all__ variable. # This relies on each of the submodules having an __all__ variable.

View file

@ -36,7 +36,7 @@ from . import tasks
from .log import logger from .log import logger
__all__ = ['BaseEventLoop'] __all__ = 'BaseEventLoop',
# Minimum number of _scheduled timer handles before cleanup of # 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,
def _run_until_complete_cb(fut): def _run_until_complete_cb(fut):
exc = fut._exception exc = fut._exception
if (isinstance(exc, BaseException) if isinstance(exc, BaseException) and not isinstance(exc, Exception):
and not isinstance(exc, Exception)):
# Issue #22429: run_forever() already finished, no need to # Issue #22429: run_forever() already finished, no need to
# stop it. # stop it.
return return
@ -190,7 +189,7 @@ class Server(events.AbstractServer):
self._waiters = [] self._waiters = []
def __repr__(self): def __repr__(self):
return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets) return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
def _attach(self): def _attach(self):
assert self.sockets is not None assert self.sockets is not None
@ -262,9 +261,10 @@ class BaseEventLoop(events.AbstractEventLoop):
self._asyncgens_shutdown_called = False self._asyncgens_shutdown_called = False
def __repr__(self): def __repr__(self):
return ('<%s running=%s closed=%s debug=%s>' return (
% (self.__class__.__name__, self.is_running(), f'<{self.__class__.__name__} running={self.is_running()} '
self.is_closed(), self.get_debug())) f'closed={self.is_closed()} debug={self.get_debug()}>'
)
def create_future(self): def create_future(self):
"""Create a Future object attached to the loop.""" """Create a Future object attached to the loop."""
@ -362,8 +362,8 @@ class BaseEventLoop(events.AbstractEventLoop):
def _asyncgen_firstiter_hook(self, agen): def _asyncgen_firstiter_hook(self, agen):
if self._asyncgens_shutdown_called: if self._asyncgens_shutdown_called:
warnings.warn( warnings.warn(
"asynchronous generator {!r} was scheduled after " f"asynchronous generator {agen!r} was scheduled after "
"loop.shutdown_asyncgens() call".format(agen), f"loop.shutdown_asyncgens() call",
ResourceWarning, source=self) ResourceWarning, source=self)
self._asyncgens.add(agen) self._asyncgens.add(agen)
@ -388,8 +388,8 @@ class BaseEventLoop(events.AbstractEventLoop):
for result, agen in zip(results, closing_agens): for result, agen in zip(results, closing_agens):
if isinstance(result, Exception): if isinstance(result, Exception):
self.call_exception_handler({ self.call_exception_handler({
'message': 'an error occurred during closing of ' 'message': f'an error occurred during closing of '
'asynchronous generator {!r}'.format(agen), f'asynchronous generator {agen!r}',
'exception': result, 'exception': result,
'asyncgen': agen 'asyncgen': agen
}) })
@ -495,7 +495,7 @@ class BaseEventLoop(events.AbstractEventLoop):
def __del__(self): def __del__(self):
if not self.is_closed(): if not self.is_closed():
warnings.warn("unclosed event loop %r" % self, ResourceWarning, warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
source=self) source=self)
if not self.is_running(): if not self.is_running():
self.close() self.close()
@ -573,12 +573,11 @@ class BaseEventLoop(events.AbstractEventLoop):
if (coroutines.iscoroutine(callback) or if (coroutines.iscoroutine(callback) or
coroutines.iscoroutinefunction(callback)): coroutines.iscoroutinefunction(callback)):
raise TypeError( raise TypeError(
"coroutines cannot be used with {}()".format(method)) f"coroutines cannot be used with {method}()")
if not callable(callback): if not callable(callback):
raise TypeError( raise TypeError(
'a callable object was expected by {}(), got {!r}'.format( f'a callable object was expected by {method}(), '
method, callback)) f'got {callback!r}')
def _call_soon(self, callback, args): def _call_soon(self, callback, args):
handle = events.Handle(callback, args, self) handle = events.Handle(callback, args, self)
@ -630,15 +629,15 @@ class BaseEventLoop(events.AbstractEventLoop):
self._default_executor = executor self._default_executor = executor
def _getaddrinfo_debug(self, host, port, family, type, proto, flags): def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
msg = ["%s:%r" % (host, port)] msg = [f"{host}:{port!r}"]
if family: if family:
msg.append('family=%r' % family) msg.append(f'family={family!r}' % family)
if type: if type:
msg.append('type=%r' % type) msg.append(f'type={type!r}')
if proto: if proto:
msg.append('proto=%r' % proto) msg.append(f'proto={proto!r}')
if flags: if flags:
msg.append('flags=%r' % flags) msg.append(f'flags={flags!r}')
msg = ', '.join(msg) msg = ', '.join(msg)
logger.debug('Get address info %s', msg) logger.debug('Get address info %s', msg)
@ -646,8 +645,7 @@ class BaseEventLoop(events.AbstractEventLoop):
addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags) addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
dt = self.time() - t0 dt = self.time() - t0
msg = ('Getting address info %s took %.3f ms: %r' msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
% (msg, dt * 1e3, addrinfo))
if dt >= self.slow_callback_duration: if dt >= self.slow_callback_duration:
logger.info(msg) logger.info(msg)
else: else:
@ -738,11 +736,12 @@ class BaseEventLoop(events.AbstractEventLoop):
sock.bind(laddr) sock.bind(laddr)
break break
except OSError as exc: except OSError as exc:
exc = OSError( msg = (
exc.errno, 'error while ' f'error while attempting to bind on '
'attempting to bind on address ' f'address {laddr!r}: '
'{!r}: {}'.format( f'{exc.strerror.lower()}'
laddr, exc.strerror.lower())) )
exc = OSError(exc.errno, msg)
exceptions.append(exc) exceptions.append(exc)
else: else:
sock.close() sock.close()
@ -786,7 +785,7 @@ class BaseEventLoop(events.AbstractEventLoop):
# Disallowing AF_UNIX in this method, breaks backwards # Disallowing AF_UNIX in this method, breaks backwards
# compatibility. # compatibility.
raise ValueError( raise ValueError(
'A Stream Socket was expected, got {!r}'.format(sock)) f'A Stream Socket was expected, got {sock!r}')
transport, protocol = await self._create_connection_transport( transport, protocol = await self._create_connection_transport(
sock, protocol_factory, ssl, server_hostname) sock, protocol_factory, ssl, server_hostname)
@ -830,7 +829,7 @@ class BaseEventLoop(events.AbstractEventLoop):
if sock is not None: if sock is not None:
if not _is_dgram_socket(sock): if not _is_dgram_socket(sock):
raise ValueError( raise ValueError(
'A UDP Socket was expected, got {!r}'.format(sock)) f'A UDP Socket was expected, got {sock!r}')
if (local_addr or remote_addr or if (local_addr or remote_addr or
family or proto or flags or family or proto or flags or
reuse_address or reuse_port or allow_broadcast): reuse_address or reuse_port or allow_broadcast):
@ -839,11 +838,10 @@ class BaseEventLoop(events.AbstractEventLoop):
family=family, proto=proto, flags=flags, family=family, proto=proto, flags=flags,
reuse_address=reuse_address, reuse_port=reuse_port, reuse_address=reuse_address, reuse_port=reuse_port,
allow_broadcast=allow_broadcast) allow_broadcast=allow_broadcast)
problems = ', '.join( problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
'{}={}'.format(k, v) for k, v in opts.items() if v)
raise ValueError( raise ValueError(
'socket modifier keyword arguments can not be used ' f'socket modifier keyword arguments can not be used '
'when sock is specified. ({})'.format(problems)) f'when sock is specified. ({problems})')
sock.setblocking(False) sock.setblocking(False)
r_addr = None r_addr = None
else: else:
@ -953,7 +951,7 @@ class BaseEventLoop(events.AbstractEventLoop):
type=socket.SOCK_STREAM, type=socket.SOCK_STREAM,
flags=flags, loop=self) flags=flags, loop=self)
if not infos: if not infos:
raise OSError('getaddrinfo({!r}) returned empty list'.format(host)) raise OSError(f'getaddrinfo({host!r}) returned empty list')
return infos return infos
async def create_server(self, protocol_factory, host=None, port=None, async def create_server(self, protocol_factory, host=None, port=None,
@ -967,8 +965,8 @@ class BaseEventLoop(events.AbstractEventLoop):
reuse_port=None): reuse_port=None):
"""Create a TCP server. """Create a TCP server.
The host parameter can be a string, in that case the TCP server is bound The host parameter can be a string, in that case the TCP server is
to host and port. bound to host and port.
The host parameter can also be a sequence of strings and in that case The host parameter can also be a sequence of strings and in that case
the TCP server is bound to all hosts of the sequence. If a host the TCP server is bound to all hosts of the sequence. If a host
@ -1046,8 +1044,7 @@ class BaseEventLoop(events.AbstractEventLoop):
if sock is None: if sock is None:
raise ValueError('Neither host/port nor sock were specified') raise ValueError('Neither host/port nor sock were specified')
if not _is_stream_socket(sock): if not _is_stream_socket(sock):
raise ValueError( raise ValueError(f'A Stream Socket was expected, got {sock!r}')
'A Stream Socket was expected, got {!r}'.format(sock))
sockets = [sock] sockets = [sock]
server = Server(self, sockets) server = Server(self, sockets)
@ -1070,8 +1067,7 @@ class BaseEventLoop(events.AbstractEventLoop):
returns a (transport, protocol) pair. returns a (transport, protocol) pair.
""" """
if not _is_stream_socket(sock): if not _is_stream_socket(sock):
raise ValueError( raise ValueError(f'A Stream Socket was expected, got {sock!r}')
'A Stream Socket was expected, got {!r}'.format(sock))
transport, protocol = await self._create_connection_transport( transport, protocol = await self._create_connection_transport(
sock, protocol_factory, ssl, '', server_side=True) sock, protocol_factory, ssl, '', server_side=True)
@ -1117,14 +1113,14 @@ class BaseEventLoop(events.AbstractEventLoop):
def _log_subprocess(self, msg, stdin, stdout, stderr): def _log_subprocess(self, msg, stdin, stdout, stderr):
info = [msg] info = [msg]
if stdin is not None: if stdin is not None:
info.append('stdin=%s' % _format_pipe(stdin)) info.append(f'stdin={_format_pipe(stdin)}')
if stdout is not None and stderr == subprocess.STDOUT: if stdout is not None and stderr == subprocess.STDOUT:
info.append('stdout=stderr=%s' % _format_pipe(stdout)) info.append(f'stdout=stderr={_format_pipe(stdout)}')
else: else:
if stdout is not None: if stdout is not None:
info.append('stdout=%s' % _format_pipe(stdout)) info.append(f'stdout={_format_pipe(stdout)}')
if stderr is not None: if stderr is not None:
info.append('stderr=%s' % _format_pipe(stderr)) info.append(f'stderr={_format_pipe(stderr)}')
logger.debug(' '.join(info)) logger.debug(' '.join(info))
async def subprocess_shell(self, protocol_factory, cmd, *, async def subprocess_shell(self, protocol_factory, cmd, *,
@ -1167,14 +1163,14 @@ class BaseEventLoop(events.AbstractEventLoop):
popen_args = (program,) + args popen_args = (program,) + args
for arg in popen_args: for arg in popen_args:
if not isinstance(arg, (str, bytes)): if not isinstance(arg, (str, bytes)):
raise TypeError("program arguments must be " raise TypeError(
"a bytes or text string, not %s" f"program arguments must be a bytes or text string, "
% type(arg).__name__) f"not {type(arg).__name__}")
protocol = protocol_factory() protocol = protocol_factory()
if self._debug: if self._debug:
# don't log parameters: they may contain sensitive information # don't log parameters: they may contain sensitive information
# (password) and may be too long # (password) and may be too long
debug_log = 'execute program %r' % program debug_log = f'execute program {program!r}'
self._log_subprocess(debug_log, stdin, stdout, stderr) self._log_subprocess(debug_log, stdin, stdout, stderr)
transport = await self._make_subprocess_transport( transport = await self._make_subprocess_transport(
protocol, popen_args, False, stdin, stdout, stderr, protocol, popen_args, False, stdin, stdout, stderr,
@ -1201,8 +1197,8 @@ class BaseEventLoop(events.AbstractEventLoop):
documentation for details about context). documentation for details about context).
""" """
if handler is not None and not callable(handler): if handler is not None and not callable(handler):
raise TypeError('A callable object or None is expected, ' raise TypeError(f'A callable object or None is expected, '
'got {!r}'.format(handler)) f'got {handler!r}')
self._exception_handler = handler self._exception_handler = handler
def default_exception_handler(self, context): def default_exception_handler(self, context):
@ -1230,10 +1226,11 @@ class BaseEventLoop(events.AbstractEventLoop):
else: else:
exc_info = False exc_info = False
if ('source_traceback' not in context if ('source_traceback' not in context and
and self._current_handle is not None self._current_handle is not None and
and self._current_handle._source_traceback): self._current_handle._source_traceback):
context['handle_traceback'] = self._current_handle._source_traceback context['handle_traceback'] = \
self._current_handle._source_traceback
log_lines = [message] log_lines = [message]
for key in sorted(context): for key in sorted(context):
@ -1250,7 +1247,7 @@ class BaseEventLoop(events.AbstractEventLoop):
value += tb.rstrip() value += tb.rstrip()
else: else:
value = repr(value) value = repr(value)
log_lines.append('{}: {}'.format(key, value)) log_lines.append(f'{key}: {value}')
logger.error('\n'.join(log_lines), exc_info=exc_info) logger.error('\n'.join(log_lines), exc_info=exc_info)
@ -1438,18 +1435,19 @@ class BaseEventLoop(events.AbstractEventLoop):
if enabled: if enabled:
if current_wrapper not in (None, wrapper): if current_wrapper not in (None, wrapper):
warnings.warn( warnings.warn(
"loop.set_debug(True): cannot set debug coroutine " f"loop.set_debug(True): cannot set debug coroutine "
"wrapper; another wrapper is already set %r" % f"wrapper; another wrapper is already set "
current_wrapper, RuntimeWarning) f"{current_wrapper!r}",
RuntimeWarning)
else: else:
set_wrapper(wrapper) set_wrapper(wrapper)
self._coroutine_wrapper_set = True self._coroutine_wrapper_set = True
else: else:
if current_wrapper not in (None, wrapper): if current_wrapper not in (None, wrapper):
warnings.warn( warnings.warn(
"loop.set_debug(False): cannot unset debug coroutine " f"loop.set_debug(False): cannot unset debug coroutine "
"wrapper; another wrapper was set %r" % f"wrapper; another wrapper was set {current_wrapper!r}",
current_wrapper, RuntimeWarning) RuntimeWarning)
else: else:
set_wrapper(None) set_wrapper(None)
self._coroutine_wrapper_set = False self._coroutine_wrapper_set = False

View file

@ -1,4 +1,4 @@
__all__ = [] __all__ = ()
import concurrent.futures._base import concurrent.futures._base
import reprlib import reprlib
@ -48,7 +48,7 @@ def _format_callbacks(cb):
cb = '{}, <{} more>, {}'.format(format_cb(cb[0]), cb = '{}, <{} more>, {}'.format(format_cb(cb[0]),
size - 2, size - 2,
format_cb(cb[-1])) format_cb(cb[-1]))
return 'cb=[%s]' % cb return f'cb=[{cb}]'
def _future_repr_info(future): def _future_repr_info(future):
@ -57,15 +57,15 @@ def _future_repr_info(future):
info = [future._state.lower()] info = [future._state.lower()]
if future._state == _FINISHED: if future._state == _FINISHED:
if future._exception is not None: if future._exception is not None:
info.append('exception={!r}'.format(future._exception)) info.append(f'exception={future._exception!r}')
else: else:
# use reprlib to limit the length of the output, especially # use reprlib to limit the length of the output, especially
# for very long strings # for very long strings
result = reprlib.repr(future._result) result = reprlib.repr(future._result)
info.append('result={}'.format(result)) info.append(f'result={result}')
if future._callbacks: if future._callbacks:
info.append(_format_callbacks(future._callbacks)) info.append(_format_callbacks(future._callbacks))
if future._source_traceback: if future._source_traceback:
frame = future._source_traceback[-1] frame = future._source_traceback[-1]
info.append('created at %s:%s' % (frame[0], frame[1])) info.append(f'created at {frame[0]}:{frame[1]}')
return info return info

View file

@ -57,9 +57,9 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
if self._closed: if self._closed:
info.append('closed') info.append('closed')
if self._pid is not None: if self._pid is not None:
info.append('pid=%s' % self._pid) info.append(f'pid={self.pid}')
if self._returncode is not None: if self._returncode is not None:
info.append('returncode=%s' % self._returncode) info.append(f'returncode={self._returncode}')
elif self._pid is not None: elif self._pid is not None:
info.append('running') info.append('running')
else: else:
@ -67,19 +67,19 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
stdin = self._pipes.get(0) stdin = self._pipes.get(0)
if stdin is not None: if stdin is not None:
info.append('stdin=%s' % stdin.pipe) info.append(f'stdin={stdin.pipe}')
stdout = self._pipes.get(1) stdout = self._pipes.get(1)
stderr = self._pipes.get(2) stderr = self._pipes.get(2)
if stdout is not None and stderr is stdout: if stdout is not None and stderr is stdout:
info.append('stdout=stderr=%s' % stdout.pipe) info.append(f'stdout=stderr={stdout.pipe}')
else: else:
if stdout is not None: if stdout is not None:
info.append('stdout=%s' % stdout.pipe) info.append(f'stdout={stdout.pipe}')
if stderr is not None: if stderr is not None:
info.append('stderr=%s' % stderr.pipe) info.append(f'stderr={stderr.pipe}')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs): def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
raise NotImplementedError raise NotImplementedError
@ -103,12 +103,13 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
continue continue
proto.pipe.close() proto.pipe.close()
if (self._proc is not None if (self._proc is not None and
# the child process finished? # has the child process finished?
and self._returncode is None self._returncode is None and
# the child process finished but the transport was not notified yet? # the child process has finished, but the
and self._proc.poll() is None # transport hasn't been notified yet?
): self._proc.poll() is None):
if self._loop.get_debug(): if self._loop.get_debug():
logger.warning('Close running child process: kill %r', self) logger.warning('Close running child process: kill %r', self)
@ -121,7 +122,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
def __del__(self): def __del__(self):
if not self._closed: if not self._closed:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self.close() self.close()
@ -206,8 +207,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
assert returncode is not None, returncode assert returncode is not None, returncode
assert self._returncode is None, self._returncode assert self._returncode is None, self._returncode
if self._loop.get_debug(): if self._loop.get_debug():
logger.info('%r exited with return code %r', logger.info('%r exited with return code %r', self, returncode)
self, returncode)
self._returncode = returncode self._returncode = returncode
if self._proc.returncode is None: if self._proc.returncode is None:
# asyncio uses a child watcher: copy the status into the Popen # asyncio uses a child watcher: copy the status into the Popen
@ -263,8 +263,7 @@ class WriteSubprocessPipeProto(protocols.BaseProtocol):
self.pipe = transport self.pipe = transport
def __repr__(self): def __repr__(self):
return ('<%s fd=%s pipe=%r>' return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'
% (self.__class__.__name__, self.fd, self.pipe))
def connection_lost(self, exc): def connection_lost(self, exc):
self.disconnected = True self.disconnected = True

View file

@ -13,10 +13,10 @@ def _task_repr_info(task):
info[0] = 'cancelling' info[0] = 'cancelling'
coro = coroutines._format_coroutine(task._coro) coro = coroutines._format_coroutine(task._coro)
info.insert(1, 'coro=<%s>' % coro) info.insert(1, f'coro=<{coro}>')
if task._fut_waiter is not None: if task._fut_waiter is not None:
info.insert(2, 'wait_for=%r' % task._fut_waiter) info.insert(2, f'wait_for={task._fut_waiter!r}')
return info return info
@ -61,15 +61,15 @@ def _task_print_stack(task, limit, file):
linecache.checkcache(filename) linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals) line = linecache.getline(filename, lineno, f.f_globals)
extracted_list.append((filename, lineno, name, line)) extracted_list.append((filename, lineno, name, line))
exc = task._exception exc = task._exception
if not extracted_list: if not extracted_list:
print('No stack for %r' % task, file=file) print(f'No stack for {task!r}', file=file)
elif exc is not None: elif exc is not None:
print('Traceback for %r (most recent call last):' % task, print(f'Traceback for {task!r} (most recent call last):', file=file)
file=file)
else: else:
print('Stack for %r (most recent call last):' % task, print(f'Stack for {task!r} (most recent call last):', file=file)
file=file)
traceback.print_list(extracted_list, file=file) traceback.print_list(extracted_list, file=file)
if exc is not None: if exc is not None:
for line in traceback.format_exception_only(exc.__class__, exc): for line in traceback.format_exception_only(exc.__class__, exc):

View file

@ -1,5 +1,3 @@
"""Constants."""
# After the connection is lost, log warnings after this many write()s. # After the connection is lost, log warnings after this many write()s.
LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5 LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5

View file

@ -1,9 +1,7 @@
__all__ = ['coroutine', __all__ = 'coroutine', 'iscoroutinefunction', 'iscoroutine'
'iscoroutinefunction', 'iscoroutine']
import functools import functools
import inspect import inspect
import opcode
import os import os
import sys import sys
import traceback import traceback
@ -27,9 +25,8 @@ def _is_debug_mode():
# before you define your coroutines. A downside of using this feature # before you define your coroutines. A downside of using this feature
# is that tracebacks show entries for the CoroWrapper.__next__ method # is that tracebacks show entries for the CoroWrapper.__next__ method
# when _DEBUG is true. # when _DEBUG is true.
return (sys.flags.dev_mode return sys.flags.dev_mode or (not sys.flags.ignore_environment and
or (not sys.flags.ignore_environment bool(os.environ.get('PYTHONASYNCIODEBUG')))
and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
_DEBUG = _is_debug_mode() _DEBUG = _is_debug_mode()
@ -58,8 +55,9 @@ class CoroWrapper:
coro_repr = _format_coroutine(self) coro_repr = _format_coroutine(self)
if self._source_traceback: if self._source_traceback:
frame = self._source_traceback[-1] frame = self._source_traceback[-1]
coro_repr += ', created at %s:%s' % (frame[0], frame[1]) coro_repr += f', created at {frame[0]}:{frame[1]}'
return '<%s %s>' % (self.__class__.__name__, coro_repr)
return f'<{self.__class__.__name__} {coro_repr}>'
def __iter__(self): def __iter__(self):
return self return self
@ -92,8 +90,8 @@ class CoroWrapper:
cr_await = getattr(self.gen, 'cr_await', None) cr_await = getattr(self.gen, 'cr_await', None)
if cr_await is not None: if cr_await is not None:
raise RuntimeError( raise RuntimeError(
"Cannot await on coroutine {!r} while it's " f"Cannot await on coroutine {self.gen!r} while it's "
"awaiting for {!r}".format(self.gen, cr_await)) f"awaiting for {cr_await!r}")
return self return self
@property @property
@ -123,7 +121,7 @@ class CoroWrapper:
if frame is None: if frame is None:
frame = getattr(gen, 'cr_frame', None) frame = getattr(gen, 'cr_frame', None)
if frame is not None and frame.f_lasti == -1: if frame is not None and frame.f_lasti == -1:
msg = '%r was never yielded from' % self msg = f'{self!r} was never yielded from'
tb = getattr(self, '_source_traceback', ()) tb = getattr(self, '_source_traceback', ())
if tb: if tb:
tb = ''.join(traceback.format_list(tb)) tb = ''.join(traceback.format_list(tb))
@ -154,11 +152,10 @@ def coroutine(func):
def coro(*args, **kw): def coro(*args, **kw):
res = func(*args, **kw) res = func(*args, **kw)
if (base_futures.isfuture(res) or inspect.isgenerator(res) or if (base_futures.isfuture(res) or inspect.isgenerator(res) or
isinstance(res, CoroWrapper)): isinstance(res, CoroWrapper)):
res = yield from res res = yield from res
else: else:
# If 'func' returns an Awaitable (new in 3.5) we # If 'res' is an awaitable, run it.
# want to run it.
try: try:
await_meth = res.__await__ await_meth = res.__await__
except AttributeError: except AttributeError:
@ -219,7 +216,7 @@ def _format_coroutine(coro):
coro_name = getattr( coro_name = getattr(
coro, '__qualname__', coro, '__qualname__',
getattr(coro, '__name__', type(coro).__name__)) getattr(coro, '__name__', type(coro).__name__))
coro_name = '{}()'.format(coro_name) coro_name = f'{coro_name}()'
running = False running = False
try: try:
@ -231,7 +228,7 @@ def _format_coroutine(coro):
pass pass
if running: if running:
return '{} running'.format(coro_name) return f'{coro_name} running'
else: else:
return coro_name return coro_name
@ -240,7 +237,7 @@ def _format_coroutine(coro):
func = coro.func func = coro.func
coro_name = coro.__qualname__ coro_name = coro.__qualname__
if coro_name is not None: if coro_name is not None:
coro_name = '{}()'.format(coro_name) coro_name = f'{coro_name}()'
else: else:
func = coro func = coro
@ -266,18 +263,14 @@ def _format_coroutine(coro):
if source is not None: if source is not None:
filename, lineno = source filename, lineno = source
if coro_frame is None: if coro_frame is None:
coro_repr = ('%s done, defined at %s:%s' coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
% (coro_name, filename, lineno))
else: else:
coro_repr = ('%s running, defined at %s:%s' coro_repr = f'{coro_name} running, defined at {filename}:{lineno}'
% (coro_name, filename, lineno))
elif coro_frame is not None: elif coro_frame is not None:
lineno = coro_frame.f_lineno lineno = coro_frame.f_lineno
coro_repr = ('%s running at %s:%s' coro_repr = f'{coro_name} running at {filename}:{lineno}'
% (coro_name, filename, lineno))
else: else:
lineno = coro_code.co_firstlineno lineno = coro_code.co_firstlineno
coro_repr = ('%s done, defined at %s:%s' coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
% (coro_name, filename, lineno))
return coro_repr return coro_repr

View file

@ -1,13 +1,14 @@
"""Event loop and event loop policy.""" """Event loop and event loop policy."""
__all__ = ['AbstractEventLoopPolicy', __all__ = (
'AbstractEventLoop', 'AbstractServer', 'AbstractEventLoopPolicy',
'Handle', 'TimerHandle', 'AbstractEventLoop', 'AbstractServer',
'get_event_loop_policy', 'set_event_loop_policy', 'Handle', 'TimerHandle',
'get_event_loop', 'set_event_loop', 'new_event_loop', 'get_event_loop_policy', 'set_event_loop_policy',
'get_child_watcher', 'set_child_watcher', 'get_event_loop', 'set_event_loop', 'new_event_loop',
'_set_running_loop', '_get_running_loop', 'get_child_watcher', 'set_child_watcher',
] '_set_running_loop', '_get_running_loop',
)
import functools import functools
import inspect import inspect
@ -44,9 +45,8 @@ def _format_args_and_kwargs(args, kwargs):
if args: if args:
items.extend(reprlib.repr(arg) for arg in args) items.extend(reprlib.repr(arg) for arg in args)
if kwargs: if kwargs:
items.extend('{}={}'.format(k, reprlib.repr(v)) items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
for k, v in kwargs.items()) return '({})'.format(', '.join(items))
return '(' + ', '.join(items) + ')'
def _format_callback(func, args, kwargs, suffix=''): def _format_callback(func, args, kwargs, suffix=''):
@ -66,11 +66,12 @@ def _format_callback(func, args, kwargs, suffix=''):
func_repr += suffix func_repr += suffix
return func_repr return func_repr
def _format_callback_source(func, args): def _format_callback_source(func, args):
func_repr = _format_callback(func, args, None) func_repr = _format_callback(func, args, None)
source = _get_function_source(func) source = _get_function_source(func)
if source: if source:
func_repr += ' at %s:%s' % source func_repr += f' at {source[0]}:{source[1]}'
return func_repr return func_repr
@ -116,14 +117,14 @@ class Handle:
info.append(_format_callback_source(self._callback, self._args)) info.append(_format_callback_source(self._callback, self._args))
if self._source_traceback: if self._source_traceback:
frame = self._source_traceback[-1] frame = self._source_traceback[-1]
info.append('created at %s:%s' % (frame[0], frame[1])) info.append(f'created at {frame[0]}:{frame[1]}')
return info return info
def __repr__(self): def __repr__(self):
if self._repr is not None: if self._repr is not None:
return self._repr return self._repr
info = self._repr_info() info = self._repr_info()
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def cancel(self): def cancel(self):
if not self._cancelled: if not self._cancelled:
@ -144,7 +145,7 @@ class Handle:
self._callback(*self._args) self._callback(*self._args)
except Exception as exc: except Exception as exc:
cb = _format_callback_source(self._callback, self._args) cb = _format_callback_source(self._callback, self._args)
msg = 'Exception in callback {}'.format(cb) msg = f'Exception in callback {cb}'
context = { context = {
'message': msg, 'message': msg,
'exception': exc, 'exception': exc,
@ -172,7 +173,7 @@ class TimerHandle(Handle):
def _repr_info(self): def _repr_info(self):
info = super()._repr_info() info = super()._repr_info()
pos = 2 if self._cancelled else 1 pos = 2 if self._cancelled else 1
info.insert(pos, 'when=%s' % self._when) info.insert(pos, f'when={self._when}')
return info return info
def __hash__(self): def __hash__(self):
@ -334,8 +335,8 @@ class AbstractEventLoop:
If host is an empty string or None all interfaces are assumed If host is an empty string or None all interfaces are assumed
and a list of multiple sockets will be returned (most likely and a list of multiple sockets will be returned (most likely
one for IPv4 and another one for IPv6). The host parameter can also be a one for IPv4 and another one for IPv6). The host parameter can also be
sequence (e.g. list) of hosts to bind to. a sequence (e.g. list) of hosts to bind to.
family can be set to either AF_INET or AF_INET6 to force the family can be set to either AF_INET or AF_INET6 to force the
socket to use IPv4 or IPv6. If not set it will be determined socket to use IPv4 or IPv6. If not set it will be determined
@ -602,12 +603,14 @@ class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
This may be None or an instance of EventLoop. This may be None or an instance of EventLoop.
""" """
if (self._local._loop is None and if (self._local._loop is None and
not self._local._set_called and not self._local._set_called and
isinstance(threading.current_thread(), threading._MainThread)): isinstance(threading.current_thread(), threading._MainThread)):
self.set_event_loop(self.new_event_loop()) self.set_event_loop(self.new_event_loop())
if self._local._loop is None: if self._local._loop is None:
raise RuntimeError('There is no current event loop in thread %r.' raise RuntimeError('There is no current event loop in thread %r.'
% threading.current_thread().name) % threading.current_thread().name)
return self._local._loop return self._local._loop
def set_event_loop(self, loop): def set_event_loop(self, loop):

View file

@ -1,12 +1,13 @@
"""A Future class similar to the one in PEP 3148.""" """A Future class similar to the one in PEP 3148."""
__all__ = ['CancelledError', 'TimeoutError', 'InvalidStateError', __all__ = (
'Future', 'wrap_future', 'isfuture'] 'CancelledError', 'TimeoutError', 'InvalidStateError',
'Future', 'wrap_future', 'isfuture',
)
import concurrent.futures import concurrent.futures
import logging import logging
import sys import sys
import traceback
from . import base_futures from . import base_futures
from . import events from . import events
@ -82,7 +83,8 @@ class Future:
_repr_info = base_futures._future_repr_info _repr_info = base_futures._future_repr_info
def __repr__(self): def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, ' '.join(self._repr_info())) return '<{} {}>'.format(self.__class__.__name__,
' '.join(self._repr_info()))
def __del__(self): def __del__(self):
if not self._log_traceback: if not self._log_traceback:
@ -91,8 +93,8 @@ class Future:
return return
exc = self._exception exc = self._exception
context = { context = {
'message': ('%s exception was never retrieved' 'message':
% self.__class__.__name__), f'{self.__class__.__name__} exception was never retrieved',
'exception': exc, 'exception': exc,
'future': self, 'future': self,
} }
@ -237,7 +239,7 @@ class Future:
assert self.done(), "yield from wasn't used with future" assert self.done(), "yield from wasn't used with future"
return self.result() # May raise too. return self.result() # May raise too.
__await__ = __iter__ # make compatible with 'await' expression __await__ = __iter__ # make compatible with 'await' expression
# Needed for testing purposes. # Needed for testing purposes.
@ -330,7 +332,7 @@ def wrap_future(future, *, loop=None):
if isfuture(future): if isfuture(future):
return future return future
assert isinstance(future, concurrent.futures.Future), \ assert isinstance(future, concurrent.futures.Future), \
'concurrent.futures.Future is expected, got {!r}'.format(future) f'concurrent.futures.Future is expected, got {future!r}'
if loop is None: if loop is None:
loop = events.get_event_loop() loop = events.get_event_loop()
new_future = loop.create_future() new_future = loop.create_future()

View file

@ -1,6 +1,6 @@
"""Synchronization primitives.""" """Synchronization primitives."""
__all__ = ['Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore'] __all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
import collections import collections
import warnings import warnings
@ -157,8 +157,8 @@ class Lock(_ContextManagerMixin):
res = super().__repr__() res = super().__repr__()
extra = 'locked' if self._locked else 'unlocked' extra = 'locked' if self._locked else 'unlocked'
if self._waiters: if self._waiters:
extra = '{},waiters:{}'.format(extra, len(self._waiters)) extra = f'{extra}, waiters:{len(self._waiters)}'
return '<{} [{}]>'.format(res[1:-1], extra) return f'<{res[1:-1]} [{extra}]>'
def locked(self): def locked(self):
"""Return True if lock is acquired.""" """Return True if lock is acquired."""
@ -233,8 +233,8 @@ class Event:
res = super().__repr__() res = super().__repr__()
extra = 'set' if self._value else 'unset' extra = 'set' if self._value else 'unset'
if self._waiters: if self._waiters:
extra = '{},waiters:{}'.format(extra, len(self._waiters)) extra = f'{extra}, waiters:{len(self._waiters)}'
return '<{} [{}]>'.format(res[1:-1], extra) return f'<{res[1:-1]} [{extra}]>'
def is_set(self): def is_set(self):
"""Return True if and only if the internal flag is true.""" """Return True if and only if the internal flag is true."""
@ -310,8 +310,8 @@ class Condition(_ContextManagerMixin):
res = super().__repr__() res = super().__repr__()
extra = 'locked' if self.locked() else 'unlocked' extra = 'locked' if self.locked() else 'unlocked'
if self._waiters: if self._waiters:
extra = '{},waiters:{}'.format(extra, len(self._waiters)) extra = f'{extra}, waiters:{len(self._waiters)}'
return '<{} [{}]>'.format(res[1:-1], extra) return f'<{res[1:-1]} [{extra}]>'
async def wait(self): async def wait(self):
"""Wait until notified. """Wait until notified.
@ -419,11 +419,10 @@ class Semaphore(_ContextManagerMixin):
def __repr__(self): def __repr__(self):
res = super().__repr__() res = super().__repr__()
extra = 'locked' if self.locked() else 'unlocked,value:{}'.format( extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
self._value)
if self._waiters: if self._waiters:
extra = '{},waiters:{}'.format(extra, len(self._waiters)) extra = f'{extra}, waiters:{len(self._waiters)}'
return '<{} [{}]>'.format(res[1:-1], extra) return f'<{res[1:-1]} [{extra}]>'
def _wake_up_next(self): def _wake_up_next(self):
while self._waiters: while self._waiters:

View file

@ -4,7 +4,7 @@ A proactor is a "notify-on-completion" multiplexer. Currently a
proactor is only implemented on Windows with IOCP. proactor is only implemented on Windows with IOCP.
""" """
__all__ = ['BaseProactorEventLoop'] __all__ = 'BaseProactorEventLoop',
import socket import socket
import warnings import warnings
@ -50,17 +50,16 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin,
elif self._closing: elif self._closing:
info.append('closing') info.append('closing')
if self._sock is not None: if self._sock is not None:
info.append('fd=%s' % self._sock.fileno()) info.append(f'fd={self._sock.fileno()}')
if self._read_fut is not None: if self._read_fut is not None:
info.append('read=%s' % self._read_fut) info.append(f'read={self._read_fut!r}')
if self._write_fut is not None: if self._write_fut is not None:
info.append("write=%r" % self._write_fut) info.append(f'write={self._write_fut!r}')
if self._buffer: if self._buffer:
bufsize = len(self._buffer) info.append(f'write_bufsize={len(self._buffer)}')
info.append('write_bufsize=%s' % bufsize)
if self._eof_written: if self._eof_written:
info.append('EOF written') info.append('EOF written')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def _set_extra(self, sock): def _set_extra(self, sock):
self._extra['pipe'] = sock self._extra['pipe'] = sock
@ -87,7 +86,7 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin,
def __del__(self): def __del__(self):
if self._sock is not None: if self._sock is not None:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self.close() self.close()
@ -227,9 +226,9 @@ class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,
def write(self, data): def write(self, data):
if not isinstance(data, (bytes, bytearray, memoryview)): if not isinstance(data, (bytes, bytearray, memoryview)):
msg = ("data argument must be a bytes-like object, not '%s'" % raise TypeError(
type(data).__name__) f"data argument must be a bytes-like object, "
raise TypeError(msg) f"not {type(data).__name__}")
if self._eof_written: if self._eof_written:
raise RuntimeError('write_eof() already called') raise RuntimeError('write_eof() already called')
@ -347,12 +346,14 @@ class _ProactorSocketTransport(_ProactorReadPipeTransport,
def _set_extra(self, sock): def _set_extra(self, sock):
self._extra['socket'] = sock self._extra['socket'] = sock
try: try:
self._extra['sockname'] = sock.getsockname() self._extra['sockname'] = sock.getsockname()
except (socket.error, AttributeError): except (socket.error, AttributeError):
if self._loop.get_debug(): if self._loop.get_debug():
logger.warning("getsockname() failed on %r", logger.warning(
sock, exc_info=True) "getsockname() failed on %r", sock, exc_info=True)
if 'peername' not in self._extra: if 'peername' not in self._extra:
try: try:
self._extra['peername'] = sock.getpeername() self._extra['peername'] = sock.getpeername()

View file

@ -1,7 +1,9 @@
"""Abstract Protocol class.""" """Abstract Protocol base classes."""
__all__ = ['BaseProtocol', 'Protocol', 'DatagramProtocol', __all__ = (
'SubprocessProtocol'] 'BaseProtocol', 'Protocol', 'DatagramProtocol',
'SubprocessProtocol',
)
class BaseProtocol: class BaseProtocol:

View file

@ -1,6 +1,4 @@
"""Queues""" __all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')
__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty']
import collections import collections
import heapq import heapq
@ -10,16 +8,12 @@ from . import locks
class QueueEmpty(Exception): class QueueEmpty(Exception):
"""Exception raised when Queue.get_nowait() is called on a Queue object """Raised when Queue.get_nowait() is called on an empty Queue."""
which is empty.
"""
pass pass
class QueueFull(Exception): class QueueFull(Exception):
"""Exception raised when the Queue.put_nowait() method is called on a Queue """Raised when the Queue.put_nowait() method is called on a full Queue."""
object which is full.
"""
pass pass
@ -73,22 +67,21 @@ class Queue:
break break
def __repr__(self): def __repr__(self):
return '<{} at {:#x} {}>'.format( return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'
type(self).__name__, id(self), self._format())
def __str__(self): def __str__(self):
return '<{} {}>'.format(type(self).__name__, self._format()) return f'<{type(self).__name__} {self._format()}>'
def _format(self): def _format(self):
result = 'maxsize={!r}'.format(self._maxsize) result = f'maxsize={self._maxsize!r}'
if getattr(self, '_queue', None): if getattr(self, '_queue', None):
result += ' _queue={!r}'.format(list(self._queue)) result += f' _queue={list(self._queue)!r}'
if self._getters: if self._getters:
result += ' _getters[{}]'.format(len(self._getters)) result += f' _getters[{len(self._getters)}]'
if self._putters: if self._putters:
result += ' _putters[{}]'.format(len(self._putters)) result += f' _putters[{len(self._putters)}]'
if self._unfinished_tasks: if self._unfinished_tasks:
result += ' tasks={}'.format(self._unfinished_tasks) result += f' tasks={self._unfinished_tasks}'
return result return result
def qsize(self): def qsize(self):

View file

@ -4,7 +4,7 @@ A selector is a "notify-when-ready" multiplexer. For a subclass which
also includes support for signal handling, see the unix_events sub-module. also includes support for signal handling, see the unix_events sub-module.
""" """
__all__ = ['BaseSelectorEventLoop'] __all__ = 'BaseSelectorEventLoop',
import collections import collections
import errno import errno
@ -184,8 +184,8 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
raise # The event loop will catch, log and ignore it. raise # The event loop will catch, log and ignore it.
else: else:
extra = {'peername': addr} extra = {'peername': addr}
accept = self._accept_connection2(protocol_factory, conn, extra, accept = self._accept_connection2(
sslcontext, server) protocol_factory, conn, extra, sslcontext, server)
self.create_task(accept) self.create_task(accept)
async def _accept_connection2(self, protocol_factory, conn, extra, async def _accept_connection2(self, protocol_factory, conn, extra,
@ -214,8 +214,8 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
except Exception as exc: except Exception as exc:
if self._debug: if self._debug:
context = { context = {
'message': ('Error on transport creation ' 'message':
'for incoming connection'), 'Error on transport creation for incoming connection',
'exception': exc, 'exception': exc,
} }
if protocol is not None: if protocol is not None:
@ -231,8 +231,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
fileno = int(fileno.fileno()) fileno = int(fileno.fileno())
except (AttributeError, TypeError, ValueError): except (AttributeError, TypeError, ValueError):
# This code matches selectors._fileobj_to_fd function. # This code matches selectors._fileobj_to_fd function.
raise ValueError("Invalid file object: " raise ValueError(f"Invalid file object: {fd!r}") from None
"{!r}".format(fd)) from None
try: try:
transport = self._transports[fileno] transport = self._transports[fileno]
except KeyError: except KeyError:
@ -240,8 +239,8 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
else: else:
if not transport.is_closing(): if not transport.is_closing():
raise RuntimeError( raise RuntimeError(
'File descriptor {!r} is used by transport {!r}'.format( f'File descriptor {fd!r} is used by transport '
fd, transport)) f'{transport!r}')
def _add_reader(self, fd, callback, *args): def _add_reader(self, fd, callback, *args):
self._check_closed() self._check_closed()
@ -389,10 +388,11 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
def _sock_recv_into(self, fut, registered_fd, sock, buf): def _sock_recv_into(self, fut, registered_fd, sock, buf):
# _sock_recv_into() can add itself as an I/O callback if the operation # _sock_recv_into() can add itself as an I/O callback if the operation
# can't be done immediately. Don't use it directly, call sock_recv_into(). # can't be done immediately. Don't use it directly, call
# sock_recv_into().
if registered_fd is not None: if registered_fd is not None:
# Remove the callback early. It should be rare that the # Remove the callback early. It should be rare that the
# selector says the fd is ready but the call still returns # selector says the FD is ready but the call still returns
# EAGAIN, and I am willing to take a hit in that case in # EAGAIN, and I am willing to take a hit in that case in
# order to simplify the common case. # order to simplify the common case.
self.remove_reader(registered_fd) self.remove_reader(registered_fd)
@ -497,7 +497,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if err != 0: if err != 0:
# Jump to any except clause below. # Jump to any except clause below.
raise OSError(err, 'Connect call failed %s' % (address,)) raise OSError(err, f'Connect call failed {address}')
except (BlockingIOError, InterruptedError): except (BlockingIOError, InterruptedError):
# socket is still registered, the callback will be retried later # socket is still registered, the callback will be retried later
pass pass
@ -596,7 +596,7 @@ class _SelectorTransport(transports._FlowControlMixin,
info.append('closed') info.append('closed')
elif self._closing: elif self._closing:
info.append('closing') info.append('closing')
info.append('fd=%s' % self._sock_fd) info.append(f'fd={self._sock_fd}')
# test if the transport was closed # test if the transport was closed
if self._loop is not None and not self._loop.is_closed(): if self._loop is not None and not self._loop.is_closed():
polling = _test_selector_event(self._loop._selector, polling = _test_selector_event(self._loop._selector,
@ -615,8 +615,8 @@ class _SelectorTransport(transports._FlowControlMixin,
state = 'idle' state = 'idle'
bufsize = self.get_write_buffer_size() bufsize = self.get_write_buffer_size()
info.append('write=<%s, bufsize=%s>' % (state, bufsize)) info.append(f'write=<{state}, bufsize={bufsize}>')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def abort(self): def abort(self):
self._force_close(None) self._force_close(None)
@ -642,7 +642,7 @@ class _SelectorTransport(transports._FlowControlMixin,
def __del__(self): def __del__(self):
if self._sock is not None: if self._sock is not None:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self._sock.close() self._sock.close()
@ -758,8 +758,8 @@ class _SelectorSocketTransport(_SelectorTransport):
def write(self, data): def write(self, data):
if not isinstance(data, (bytes, bytearray, memoryview)): if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be a bytes-like object, ' raise TypeError(f'data argument must be a bytes-like object, '
'not %r' % type(data).__name__) f'not {type(data).__name__!r}')
if self._eof: if self._eof:
raise RuntimeError('Cannot call write() after write_eof()') raise RuntimeError('Cannot call write() after write_eof()')
if not data: if not data:
@ -862,14 +862,14 @@ class _SelectorDatagramTransport(_SelectorTransport):
def sendto(self, data, addr=None): def sendto(self, data, addr=None):
if not isinstance(data, (bytes, bytearray, memoryview)): if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be a bytes-like object, ' raise TypeError(f'data argument must be a bytes-like object, '
'not %r' % type(data).__name__) f'not {type(data).__name__!r}')
if not data: if not data:
return return
if self._address and addr not in (None, self._address): if self._address and addr not in (None, self._address):
raise ValueError('Invalid address: must be None or %s' % raise ValueError(
(self._address,)) f'Invalid address: must be None or {self._address}')
if self._conn_lost and self._address: if self._conn_lost and self._address:
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES: if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
@ -891,8 +891,8 @@ class _SelectorDatagramTransport(_SelectorTransport):
self._protocol.error_received(exc) self._protocol.error_received(exc)
return return
except Exception as exc: except Exception as exc:
self._fatal_error(exc, self._fatal_error(
'Fatal write error on datagram transport') exc, 'Fatal write error on datagram transport')
return return
# Ensure that what we buffer is immutable. # Ensure that what we buffer is immutable.
@ -914,8 +914,8 @@ class _SelectorDatagramTransport(_SelectorTransport):
self._protocol.error_received(exc) self._protocol.error_received(exc)
return return
except Exception as exc: except Exception as exc:
self._fatal_error(exc, self._fatal_error(
'Fatal write error on datagram transport') exc, 'Fatal write error on datagram transport')
return return
self._maybe_resume_protocol() # May append to buffer. self._maybe_resume_protocol() # May append to buffer.

View file

@ -313,7 +313,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin,
def __del__(self): def __del__(self):
if not self._closed: if not self._closed:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self.close() self.close()
@ -365,8 +365,8 @@ class _SSLProtocolTransport(transports._FlowControlMixin,
to be sent out asynchronously. to be sent out asynchronously.
""" """
if not isinstance(data, (bytes, bytearray, memoryview)): if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecting a bytes-like instance, got {!r}" raise TypeError(f"data: expecting a bytes-like instance, "
.format(type(data).__name__)) f"got {type(data).__name__}")
if not data: if not data:
return return
self._ssl_protocol._write_appdata(data) self._ssl_protocol._write_appdata(data)
@ -399,7 +399,8 @@ class SSLProtocol(protocols.Protocol):
raise RuntimeError('stdlib ssl module not available') raise RuntimeError('stdlib ssl module not available')
if not sslcontext: if not sslcontext:
sslcontext = _create_transport_context(server_side, server_hostname) sslcontext = _create_transport_context(
server_side, server_hostname)
self._server_side = server_side self._server_side = server_side
if server_hostname and not server_side: if server_hostname and not server_side:
@ -567,8 +568,8 @@ class SSLProtocol(protocols.Protocol):
if not hasattr(self._sslcontext, 'check_hostname'): if not hasattr(self._sslcontext, 'check_hostname'):
# Verify hostname if requested, Python 3.4+ uses check_hostname # Verify hostname if requested, Python 3.4+ uses check_hostname
# and checks the hostname in do_handshake() # and checks the hostname in do_handshake()
if (self._server_hostname if (self._server_hostname and
and self._sslcontext.verify_mode != ssl.CERT_NONE): self._sslcontext.verify_mode != ssl.CERT_NONE):
ssl.match_hostname(peercert, self._server_hostname) ssl.match_hostname(peercert, self._server_hostname)
except BaseException as exc: except BaseException as exc:
if self._loop.get_debug(): if self._loop.get_debug():

View file

@ -1,15 +1,13 @@
"""Stream-related things.""" __all__ = (
'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
__all__ = ['StreamReader', 'StreamWriter', 'StreamReaderProtocol', 'open_connection', 'start_server',
'open_connection', 'start_server', 'IncompleteReadError', 'LimitOverrunError',
'IncompleteReadError', )
'LimitOverrunError',
]
import socket import socket
if hasattr(socket, 'AF_UNIX'): if hasattr(socket, 'AF_UNIX'):
__all__.extend(['open_unix_connection', 'start_unix_server']) __all__ += ('open_unix_connection', 'start_unix_server')
from . import coroutines from . import coroutines
from . import events from . import events
@ -29,8 +27,8 @@ class IncompleteReadError(EOFError):
- expected: total number of expected bytes (or None if unknown) - expected: total number of expected bytes (or None if unknown)
""" """
def __init__(self, partial, expected): def __init__(self, partial, expected):
super().__init__("%d bytes read on a total of %r expected bytes" super().__init__(f'{len(partial)} bytes read on a total of '
% (len(partial), expected)) f'{expected!r} expected bytes')
self.partial = partial self.partial = partial
self.expected = expected self.expected = expected
@ -281,10 +279,10 @@ class StreamWriter:
self._loop = loop self._loop = loop
def __repr__(self): def __repr__(self):
info = [self.__class__.__name__, 'transport=%r' % self._transport] info = [self.__class__.__name__, f'transport={self._transport!r}']
if self._reader is not None: if self._reader is not None:
info.append('reader=%r' % self._reader) info.append(f'reader={self._reader!r}')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
@property @property
def transport(self): def transport(self):
@ -356,20 +354,20 @@ class StreamReader:
def __repr__(self): def __repr__(self):
info = ['StreamReader'] info = ['StreamReader']
if self._buffer: if self._buffer:
info.append('%d bytes' % len(self._buffer)) info.append(f'{len(self._buffer)} bytes')
if self._eof: if self._eof:
info.append('eof') info.append('eof')
if self._limit != _DEFAULT_LIMIT: if self._limit != _DEFAULT_LIMIT:
info.append('l=%d' % self._limit) info.append(f'limit={self._limit}')
if self._waiter: if self._waiter:
info.append('w=%r' % self._waiter) info.append(f'waiter={self._waiter!r}')
if self._exception: if self._exception:
info.append('e=%r' % self._exception) info.append(f'exception={self._exception!r}')
if self._transport: if self._transport:
info.append('t=%r' % self._transport) info.append(f'transport={self._transport!r}')
if self._paused: if self._paused:
info.append('paused') info.append('paused')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def exception(self): def exception(self):
return self._exception return self._exception
@ -440,8 +438,9 @@ class StreamReader:
# would have an unexpected behaviour. It would not possible to know # would have an unexpected behaviour. It would not possible to know
# which coroutine would get the next data. # which coroutine would get the next data.
if self._waiter is not None: if self._waiter is not None:
raise RuntimeError('%s() called while another coroutine is ' raise RuntimeError(
'already waiting for incoming data' % func_name) f'{func_name}() called while another coroutine is '
f'already waiting for incoming data')
assert not self._eof, '_wait_for_data after EOF' assert not self._eof, '_wait_for_data after EOF'

View file

@ -1,4 +1,4 @@
__all__ = ['create_subprocess_exec', 'create_subprocess_shell'] __all__ = 'create_subprocess_exec', 'create_subprocess_shell'
import subprocess import subprocess
@ -29,12 +29,12 @@ class SubprocessStreamProtocol(streams.FlowControlMixin,
def __repr__(self): def __repr__(self):
info = [self.__class__.__name__] info = [self.__class__.__name__]
if self.stdin is not None: if self.stdin is not None:
info.append('stdin=%r' % self.stdin) info.append(f'stdin={self.stdin!r}')
if self.stdout is not None: if self.stdout is not None:
info.append('stdout=%r' % self.stdout) info.append(f'stdout={self.stdout!r}')
if self.stderr is not None: if self.stderr is not None:
info.append('stderr=%r' % self.stderr) info.append(f'stderr={self.stderr!r}')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def connection_made(self, transport): def connection_made(self, transport):
self._transport = transport self._transport = transport
@ -83,7 +83,7 @@ class SubprocessStreamProtocol(streams.FlowControlMixin,
reader = self.stderr reader = self.stderr
else: else:
reader = None reader = None
if reader != None: if reader is not None:
if exc is None: if exc is None:
reader.feed_eof() reader.feed_eof()
else: else:
@ -114,7 +114,7 @@ class Process:
self.pid = transport.get_pid() self.pid = transport.get_pid()
def __repr__(self): def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.pid) return f'<{self.__class__.__name__} {self.pid}>'
@property @property
def returncode(self): def returncode(self):
@ -137,8 +137,8 @@ class Process:
debug = self._loop.get_debug() debug = self._loop.get_debug()
self.stdin.write(input) self.stdin.write(input)
if debug: if debug:
logger.debug('%r communicate: feed stdin (%s bytes)', logger.debug(
self, len(input)) '%r communicate: feed stdin (%s bytes)', self, len(input))
try: try:
await self.stdin.drain() await self.stdin.drain()
except (BrokenPipeError, ConnectionResetError) as exc: except (BrokenPipeError, ConnectionResetError) as exc:

View file

@ -1,10 +1,11 @@
"""Support for tasks, coroutines and the scheduler.""" """Support for tasks, coroutines and the scheduler."""
__all__ = ['Task', __all__ = (
'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED', 'Task',
'wait', 'wait_for', 'as_completed', 'sleep', 'async', 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe', 'wait', 'wait_for', 'as_completed', 'sleep', 'async',
] 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
)
import concurrent.futures import concurrent.futures
import functools import functools
@ -158,8 +159,7 @@ class Task(futures.Future):
return True return True
def _step(self, exc=None): def _step(self, exc=None):
assert not self.done(), \ assert not self.done(), f'_step(): already done: {self!r}, {exc!r}'
'_step(): already done: {!r}, {!r}'.format(self, exc)
if self._must_cancel: if self._must_cancel:
if not isinstance(exc, futures.CancelledError): if not isinstance(exc, futures.CancelledError):
exc = futures.CancelledError() exc = futures.CancelledError()
@ -195,18 +195,15 @@ class Task(futures.Future):
if blocking is not None: if blocking is not None:
# Yielded Future must come from Future.__iter__(). # Yielded Future must come from Future.__iter__().
if result._loop is not self._loop: if result._loop is not self._loop:
self._loop.call_soon( new_exc = RuntimeError(
self._step, f'Task {self!r} got Future '
RuntimeError( f'{result!r} attached to a different loop')
'Task {!r} got Future {!r} attached to a ' self._loop.call_soon(self._step, new_exc)
'different loop'.format(self, result)))
elif blocking: elif blocking:
if result is self: if result is self:
self._loop.call_soon( new_exc = RuntimeError(
self._step, f'Task cannot await on itself: {self!r}')
RuntimeError( self._loop.call_soon(self._step, new_exc)
'Task cannot await on itself: {!r}'.format(
self)))
else: else:
result._asyncio_future_blocking = False result._asyncio_future_blocking = False
result.add_done_callback(self._wakeup) result.add_done_callback(self._wakeup)
@ -215,28 +212,24 @@ class Task(futures.Future):
if self._fut_waiter.cancel(): if self._fut_waiter.cancel():
self._must_cancel = False self._must_cancel = False
else: else:
self._loop.call_soon( new_exc = RuntimeError(
self._step, f'yield was used instead of yield from '
RuntimeError( f'in task {self!r} with {result!r}')
'yield was used instead of yield from ' self._loop.call_soon(self._step, new_exc)
'in task {!r} with {!r}'.format(self, result)))
elif result is None: elif result is None:
# Bare yield relinquishes control for one event loop iteration. # Bare yield relinquishes control for one event loop iteration.
self._loop.call_soon(self._step) self._loop.call_soon(self._step)
elif inspect.isgenerator(result): elif inspect.isgenerator(result):
# Yielding a generator is just wrong. # Yielding a generator is just wrong.
self._loop.call_soon( new_exc = RuntimeError(
self._step, f'yield was used instead of yield from for '
RuntimeError( f'generator in task {self!r} with {result}')
'yield was used instead of yield from for ' self._loop.call_soon(self._step, new_exc)
'generator in task {!r} with {}'.format(
self, result)))
else: else:
# Yielding something else is an error. # Yielding something else is an error.
self._loop.call_soon( new_exc = RuntimeError(f'Task got bad yield: {result!r}')
self._step, self._loop.call_soon(self._step, new_exc)
RuntimeError(
'Task got bad yield: {!r}'.format(result)))
finally: finally:
self.__class__._current_tasks.pop(self._loop) self.__class__._current_tasks.pop(self._loop)
self = None # Needed to break cycles when an exception occurs. self = None # Needed to break cycles when an exception occurs.
@ -294,11 +287,11 @@ async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
when the timeout occurs are returned in the second set. when the timeout occurs are returned in the second set.
""" """
if futures.isfuture(fs) or coroutines.iscoroutine(fs): if futures.isfuture(fs) or coroutines.iscoroutine(fs):
raise TypeError("expect a list of futures, not %s" % type(fs).__name__) raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
if not fs: if not fs:
raise ValueError('Set of coroutines/Futures is empty.') raise ValueError('Set of coroutines/Futures is empty.')
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED): if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
raise ValueError('Invalid return_when value: {}'.format(return_when)) raise ValueError(f'Invalid return_when value: {return_when}')
if loop is None: if loop is None:
loop = events.get_event_loop() loop = events.get_event_loop()
@ -430,7 +423,7 @@ def as_completed(fs, *, loop=None, timeout=None):
Note: The futures 'f' are not necessarily members of fs. Note: The futures 'f' are not necessarily members of fs.
""" """
if futures.isfuture(fs) or coroutines.iscoroutine(fs): if futures.isfuture(fs) or coroutines.iscoroutine(fs):
raise TypeError("expect a list of futures, not %s" % type(fs).__name__) raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
loop = loop if loop is not None else events.get_event_loop() loop = loop if loop is not None else events.get_event_loop()
todo = {ensure_future(f, loop=loop) for f in set(fs)} todo = {ensure_future(f, loop=loop) for f in set(fs)}
from .queues import Queue # Import here to avoid circular import problem. from .queues import Queue # Import here to avoid circular import problem.

View file

@ -1,8 +1,9 @@
"""Abstract Transport class.""" """Abstract Transport class."""
__all__ = ['BaseTransport', 'ReadTransport', 'WriteTransport', __all__ = (
'Transport', 'DatagramTransport', 'SubprocessTransport', 'BaseTransport', 'ReadTransport', 'WriteTransport',
] 'Transport', 'DatagramTransport', 'SubprocessTransport',
)
class BaseTransport: class BaseTransport:
@ -267,7 +268,7 @@ class _FlowControlMixin(Transport):
def _maybe_resume_protocol(self): def _maybe_resume_protocol(self):
if (self._protocol_paused and if (self._protocol_paused and
self.get_write_buffer_size() <= self._low_water): self.get_write_buffer_size() <= self._low_water):
self._protocol_paused = False self._protocol_paused = False
try: try:
self._protocol.resume_writing() self._protocol.resume_writing()
@ -285,14 +286,16 @@ class _FlowControlMixin(Transport):
def _set_write_buffer_limits(self, high=None, low=None): def _set_write_buffer_limits(self, high=None, low=None):
if high is None: if high is None:
if low is None: if low is None:
high = 64*1024 high = 64 * 1024
else: else:
high = 4*low high = 4 * low
if low is None: if low is None:
low = high // 4 low = high // 4
if not high >= low >= 0: if not high >= low >= 0:
raise ValueError('high (%r) must be >= low (%r) must be >= 0' % raise ValueError(
(high, low)) f'high ({high!r}) must be >= low ({low!r}) must be >= 0')
self._high_water = high self._high_water = high
self._low_water = low self._low_water = low

View file

@ -23,10 +23,12 @@ from . import transports
from .log import logger from .log import logger
__all__ = ['SelectorEventLoop', __all__ = (
'AbstractChildWatcher', 'SafeChildWatcher', 'SelectorEventLoop',
'FastChildWatcher', 'DefaultEventLoopPolicy', 'AbstractChildWatcher', 'SafeChildWatcher',
] 'FastChildWatcher', 'DefaultEventLoopPolicy',
)
if sys.platform == 'win32': # pragma: no cover if sys.platform == 'win32': # pragma: no cover
raise ImportError('Signals are not really supported on Windows') raise ImportError('Signals are not really supported on Windows')
@ -65,8 +67,8 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
Raise ValueError if the signal number is invalid or uncatchable. Raise ValueError if the signal number is invalid or uncatchable.
Raise RuntimeError if there is a problem setting up the handler. Raise RuntimeError if there is a problem setting up the handler.
""" """
if (coroutines.iscoroutine(callback) if (coroutines.iscoroutine(callback) or
or coroutines.iscoroutinefunction(callback)): coroutines.iscoroutinefunction(callback)):
raise TypeError("coroutines cannot be used " raise TypeError("coroutines cannot be used "
"with add_signal_handler()") "with add_signal_handler()")
self._check_signal(sig) self._check_signal(sig)
@ -100,7 +102,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
logger.info('set_wakeup_fd(-1) failed: %s', nexc) logger.info('set_wakeup_fd(-1) failed: %s', nexc)
if exc.errno == errno.EINVAL: if exc.errno == errno.EINVAL:
raise RuntimeError('sig {} cannot be caught'.format(sig)) raise RuntimeError(f'sig {sig} cannot be caught')
else: else:
raise raise
@ -134,7 +136,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
signal.signal(sig, handler) signal.signal(sig, handler)
except OSError as exc: except OSError as exc:
if exc.errno == errno.EINVAL: if exc.errno == errno.EINVAL:
raise RuntimeError('sig {} cannot be caught'.format(sig)) raise RuntimeError(f'sig {sig} cannot be caught')
else: else:
raise raise
@ -153,11 +155,10 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
Raise RuntimeError if there is a problem setting up the handler. Raise RuntimeError if there is a problem setting up the handler.
""" """
if not isinstance(sig, int): if not isinstance(sig, int):
raise TypeError('sig must be an int, not {!r}'.format(sig)) raise TypeError(f'sig must be an int, not {sig!r}')
if not (1 <= sig < signal.NSIG): if not (1 <= sig < signal.NSIG):
raise ValueError( raise ValueError(f'sig {sig} out of range(1, {signal.NSIG})')
'sig {} out of range(1, {})'.format(sig, signal.NSIG))
def _make_read_pipe_transport(self, pipe, protocol, waiter=None, def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
extra=None): extra=None):
@ -223,8 +224,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
if (sock.family != socket.AF_UNIX or if (sock.family != socket.AF_UNIX or
not base_events._is_stream_socket(sock)): not base_events._is_stream_socket(sock)):
raise ValueError( raise ValueError(
'A UNIX Domain Stream Socket was expected, got {!r}' f'A UNIX Domain Stream Socket was expected, got {sock!r}')
.format(sock))
sock.setblocking(False) sock.setblocking(False)
transport, protocol = await self._create_connection_transport( transport, protocol = await self._create_connection_transport(
@ -263,7 +263,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
if exc.errno == errno.EADDRINUSE: if exc.errno == errno.EADDRINUSE:
# Let's improve the error message by adding # Let's improve the error message by adding
# with what exact address it occurs. # with what exact address it occurs.
msg = 'Address {!r} is already in use'.format(path) msg = f'Address {path!r} is already in use'
raise OSError(errno.EADDRINUSE, msg) from None raise OSError(errno.EADDRINUSE, msg) from None
else: else:
raise raise
@ -278,8 +278,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
if (sock.family != socket.AF_UNIX or if (sock.family != socket.AF_UNIX or
not base_events._is_stream_socket(sock)): not base_events._is_stream_socket(sock)):
raise ValueError( raise ValueError(
'A UNIX Domain Stream Socket was expected, got {!r}' f'A UNIX Domain Stream Socket was expected, got {sock!r}')
.format(sock))
server = base_events.Server(self, [sock]) server = base_events.Server(self, [sock])
sock.listen(backlog) sock.listen(backlog)
@ -327,12 +326,11 @@ class _UnixReadPipeTransport(transports.ReadTransport):
info.append('closed') info.append('closed')
elif self._closing: elif self._closing:
info.append('closing') info.append('closing')
info.append('fd=%s' % self._fileno) info.append(f'fd={self._fileno}')
selector = getattr(self._loop, '_selector', None) selector = getattr(self._loop, '_selector', None)
if self._pipe is not None and selector is not None: if self._pipe is not None and selector is not None:
polling = selector_events._test_selector_event( polling = selector_events._test_selector_event(
selector, selector, self._fileno, selectors.EVENT_READ)
self._fileno, selectors.EVENT_READ)
if polling: if polling:
info.append('polling') info.append('polling')
else: else:
@ -341,7 +339,7 @@ class _UnixReadPipeTransport(transports.ReadTransport):
info.append('open') info.append('open')
else: else:
info.append('closed') info.append('closed')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def _read_ready(self): def _read_ready(self):
try: try:
@ -382,7 +380,7 @@ class _UnixReadPipeTransport(transports.ReadTransport):
def __del__(self): def __del__(self):
if self._pipe is not None: if self._pipe is not None:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self._pipe.close() self._pipe.close()
@ -461,24 +459,23 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
info.append('closed') info.append('closed')
elif self._closing: elif self._closing:
info.append('closing') info.append('closing')
info.append('fd=%s' % self._fileno) info.append(f'fd={self._fileno}')
selector = getattr(self._loop, '_selector', None) selector = getattr(self._loop, '_selector', None)
if self._pipe is not None and selector is not None: if self._pipe is not None and selector is not None:
polling = selector_events._test_selector_event( polling = selector_events._test_selector_event(
selector, selector, self._fileno, selectors.EVENT_WRITE)
self._fileno, selectors.EVENT_WRITE)
if polling: if polling:
info.append('polling') info.append('polling')
else: else:
info.append('idle') info.append('idle')
bufsize = self.get_write_buffer_size() bufsize = self.get_write_buffer_size()
info.append('bufsize=%s' % bufsize) info.append(f'bufsize={bufsize}')
elif self._pipe is not None: elif self._pipe is not None:
info.append('open') info.append('open')
else: else:
info.append('closed') info.append('closed')
return '<%s>' % ' '.join(info) return '<{}>'.format(' '.join(info))
def get_write_buffer_size(self): def get_write_buffer_size(self):
return len(self._buffer) return len(self._buffer)
@ -579,7 +576,7 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
def __del__(self): def __del__(self):
if self._pipe is not None: if self._pipe is not None:
warnings.warn("unclosed transport %r" % self, ResourceWarning, warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
source=self) source=self)
self._pipe.close() self._pipe.close()
@ -1007,5 +1004,6 @@ class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
self._watcher = watcher self._watcher = watcher
SelectorEventLoop = _UnixSelectorEventLoop SelectorEventLoop = _UnixSelectorEventLoop
DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy

View file

@ -18,9 +18,10 @@ from . import windows_utils
from .log import logger from .log import logger
__all__ = ['SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor', __all__ = (
'DefaultEventLoopPolicy', 'SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
] 'DefaultEventLoopPolicy',
)
NULL = 0 NULL = 0
@ -51,7 +52,7 @@ class _OverlappedFuture(futures.Future):
info = super()._repr_info() info = super()._repr_info()
if self._ov is not None: if self._ov is not None:
state = 'pending' if self._ov.pending else 'completed' state = 'pending' if self._ov.pending else 'completed'
info.insert(1, 'overlapped=<%s, %#x>' % (state, self._ov.address)) info.insert(1, f'overlapped=<{state}, {self._ov.address:#x}>')
return info return info
def _cancel_overlapped(self): def _cancel_overlapped(self):
@ -107,12 +108,12 @@ class _BaseWaitHandleFuture(futures.Future):
def _repr_info(self): def _repr_info(self):
info = super()._repr_info() info = super()._repr_info()
info.append('handle=%#x' % self._handle) info.append(f'handle={self._handle:#x}')
if self._handle is not None: if self._handle is not None:
state = 'signaled' if self._poll() else 'waiting' state = 'signaled' if self._poll() else 'waiting'
info.append(state) info.append(state)
if self._wait_handle is not None: if self._wait_handle is not None:
info.append('wait_handle=%#x' % self._wait_handle) info.append(f'wait_handle={self._wait_handle:#x}')
return info return info
def _unregister_wait_cb(self, fut): def _unregister_wait_cb(self, fut):
@ -543,9 +544,9 @@ class IocpProactor:
async def connect_pipe(self, address): async def connect_pipe(self, address):
delay = CONNECT_PIPE_INIT_DELAY delay = CONNECT_PIPE_INIT_DELAY
while True: while True:
# Unfortunately there is no way to do an overlapped connect to a pipe. # Unfortunately there is no way to do an overlapped connect to
# Call CreateFile() in a loop until it doesn't fail with # a pipe. Call CreateFile() in a loop until it doesn't fail with
# ERROR_PIPE_BUSY # ERROR_PIPE_BUSY.
try: try:
handle = _overlapped.ConnectPipe(address) handle = _overlapped.ConnectPipe(address)
break break

View file

@ -1,6 +1,4 @@
""" """Various Windows specific bits and pieces."""
Various Windows specific bits and pieces
"""
import sys import sys
@ -11,13 +9,12 @@ import _winapi
import itertools import itertools
import msvcrt import msvcrt
import os import os
import socket
import subprocess import subprocess
import tempfile import tempfile
import warnings import warnings
__all__ = ['pipe', 'Popen', 'PIPE', 'PipeHandle'] __all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'
# Constants/globals # Constants/globals
@ -34,8 +31,9 @@ _mmap_counter = itertools.count()
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE): def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
"""Like os.pipe() but with overlapped support and using handles not fds.""" """Like os.pipe() but with overlapped support and using handles not fds."""
address = tempfile.mktemp(prefix=r'\\.\pipe\python-pipe-%d-%d-' % address = tempfile.mktemp(
(os.getpid(), next(_mmap_counter))) prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
os.getpid(), next(_mmap_counter)))
if duplex: if duplex:
openmode = _winapi.PIPE_ACCESS_DUPLEX openmode = _winapi.PIPE_ACCESS_DUPLEX
@ -90,10 +88,10 @@ class PipeHandle:
def __repr__(self): def __repr__(self):
if self._handle is not None: if self._handle is not None:
handle = 'handle=%r' % self._handle handle = f'handle={self._handle!r}'
else: else:
handle = 'closed' handle = 'closed'
return '<%s %s>' % (self.__class__.__name__, handle) return f'<{self.__class__.__name__} {handle}>'
@property @property
def handle(self): def handle(self):
@ -111,7 +109,7 @@ class PipeHandle:
def __del__(self): def __del__(self):
if self._handle is not None: if self._handle is not None:
warnings.warn("unclosed %r" % self, ResourceWarning, warnings.warn(f"unclosed {self!r}", ResourceWarning,
source=self) source=self)
self.close() self.close()

View file

@ -10,7 +10,7 @@ from asyncio import test_utils
STR_RGX_REPR = ( STR_RGX_REPR = (
r'^<(?P<class>.*?) object at (?P<address>.*?)' r'^<(?P<class>.*?) object at (?P<address>.*?)'
r'\[(?P<extras>' r'\[(?P<extras>'
r'(set|unset|locked|unlocked)(,value:\d)?(,waiters:\d+)?' r'(set|unset|locked|unlocked)(, value:\d)?(, waiters:\d+)?'
r')\]>\Z' r')\]>\Z'
) )
RGX_REPR = re.compile(STR_RGX_REPR) RGX_REPR = re.compile(STR_RGX_REPR)
@ -760,7 +760,7 @@ class SemaphoreTests(test_utils.TestCase):
def test_repr(self): def test_repr(self):
sem = asyncio.Semaphore(loop=self.loop) sem = asyncio.Semaphore(loop=self.loop)
self.assertTrue(repr(sem).endswith('[unlocked,value:1]>')) self.assertTrue(repr(sem).endswith('[unlocked, value:1]>'))
self.assertTrue(RGX_REPR.match(repr(sem))) self.assertTrue(RGX_REPR.match(repr(sem)))
self.loop.run_until_complete(sem.acquire()) self.loop.run_until_complete(sem.acquire())

View file

@ -806,7 +806,7 @@ os.close(fd)
def test___repr__nondefault_limit(self): def test___repr__nondefault_limit(self):
stream = asyncio.StreamReader(loop=self.loop, limit=123) stream = asyncio.StreamReader(loop=self.loop, limit=123)
self.assertEqual("<StreamReader l=123>", repr(stream)) self.assertEqual("<StreamReader limit=123>", repr(stream))
def test___repr__eof(self): def test___repr__eof(self):
stream = asyncio.StreamReader(loop=self.loop) stream = asyncio.StreamReader(loop=self.loop)
@ -822,14 +822,15 @@ os.close(fd)
stream = asyncio.StreamReader(loop=self.loop) stream = asyncio.StreamReader(loop=self.loop)
exc = RuntimeError() exc = RuntimeError()
stream.set_exception(exc) stream.set_exception(exc)
self.assertEqual("<StreamReader e=RuntimeError()>", repr(stream)) self.assertEqual("<StreamReader exception=RuntimeError()>",
repr(stream))
def test___repr__waiter(self): def test___repr__waiter(self):
stream = asyncio.StreamReader(loop=self.loop) stream = asyncio.StreamReader(loop=self.loop)
stream._waiter = asyncio.Future(loop=self.loop) stream._waiter = asyncio.Future(loop=self.loop)
self.assertRegex( self.assertRegex(
repr(stream), repr(stream),
r"<StreamReader w=<Future pending[\S ]*>>") r"<StreamReader waiter=<Future pending[\S ]*>>")
stream._waiter.set_result(None) stream._waiter.set_result(None)
self.loop.run_until_complete(stream._waiter) self.loop.run_until_complete(stream._waiter)
stream._waiter = None stream._waiter = None
@ -840,7 +841,7 @@ os.close(fd)
stream._transport = mock.Mock() stream._transport = mock.Mock()
stream._transport.__repr__ = mock.Mock() stream._transport.__repr__ = mock.Mock()
stream._transport.__repr__.return_value = "<Transport>" stream._transport.__repr__.return_value = "<Transport>"
self.assertEqual("<StreamReader t=<Transport>>", repr(stream)) self.assertEqual("<StreamReader transport=<Transport>>", repr(stream))
def test_IncompleteReadError_pickleable(self): def test_IncompleteReadError_pickleable(self):
e = asyncio.IncompleteReadError(b'abc', 10) e = asyncio.IncompleteReadError(b'abc', 10)