Skip to content

Commit cc83920

Browse files
authored
bpo-32166: Drop Python 3.4 code from asyncio (#4612)
* Drop Python 3.4 code from asyncio * Fix notes * Add missing imports * Restore comment * Resort imports * Drop Python 3.4-3.5 specific code * Drop redunant check * Fix tests * Restore _COROUTINE_TYPES order * Remove useless code
1 parent 5d39e04 commit cc83920

3 files changed

Lines changed: 25 additions & 131 deletions

File tree

‎Lib/asyncio/coroutines.py‎

Lines changed: 14 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,14 @@
99
import traceback
1010
import types
1111

12+
from collections.abc import Awaitable, Coroutine
13+
1214
from . import constants
1315
from . import events
1416
from . import base_futures
1517
from .log import logger
1618

1719

18-
# Opcode of "yield from" instruction
19-
_YIELD_FROM = opcode.opmap['YIELD_FROM']
20-
21-
2220
def _is_debug_mode():
2321
# If you set _DEBUG to true, @coroutine will wrap the resulting
2422
# generator objects in a CoroWrapper instance (defined below). That
@@ -39,51 +37,6 @@ def _is_debug_mode():
3937
_DEBUG = _is_debug_mode()
4038

4139

42-
try:
43-
_types_coroutine = types.coroutine
44-
_types_CoroutineType = types.CoroutineType
45-
except AttributeError:
46-
# Python 3.4
47-
_types_coroutine = None
48-
_types_CoroutineType = None
49-
50-
try:
51-
_inspect_iscoroutinefunction = inspect.iscoroutinefunction
52-
except AttributeError:
53-
# Python 3.4
54-
_inspect_iscoroutinefunction = lambda func: False
55-
56-
try:
57-
from collections.abc import Coroutine as _CoroutineABC, \
58-
Awaitable as _AwaitableABC
59-
except ImportError:
60-
_CoroutineABC = _AwaitableABC = None
61-
62-
63-
# Check for CPython issue #21209
64-
def has_yield_from_bug():
65-
class MyGen:
66-
def __init__(self):
67-
self.send_args = None
68-
def __iter__(self):
69-
return self
70-
def __next__(self):
71-
return 42
72-
def send(self, *what):
73-
self.send_args = what
74-
return None
75-
def yield_from_gen(gen):
76-
yield from gen
77-
value = (1, 2, 3)
78-
gen = MyGen()
79-
coro = yield_from_gen(gen)
80-
next(coro)
81-
coro.send(value)
82-
return gen.send_args != (value,)
83-
_YIELD_FROM_BUG = has_yield_from_bug()
84-
del has_yield_from_bug
85-
86-
8740
def debug_wrapper(gen):
8841
# This function is called from 'sys.set_coroutine_wrapper'.
8942
# We only wrap here coroutines defined via 'async def' syntax.
@@ -116,21 +69,8 @@ def __iter__(self):
11669
def __next__(self):
11770
return self.gen.send(None)
11871

119-
if _YIELD_FROM_BUG:
120-
# For for CPython issue #21209: using "yield from" and a custom
121-
# generator, generator.send(tuple) unpacks the tuple instead of passing
122-
# the tuple unchanged. Check if the caller is a generator using "yield
123-
# from" to decide if the parameter should be unpacked or not.
124-
def send(self, *value):
125-
frame = sys._getframe()
126-
caller = frame.f_back
127-
assert caller.f_lasti >= 0
128-
if caller.f_code.co_code[caller.f_lasti] != _YIELD_FROM:
129-
value = value[0]
130-
return self.gen.send(value)
131-
else:
132-
def send(self, value):
133-
return self.gen.send(value)
72+
def send(self, value):
73+
return self.gen.send(value)
13474

13575
def throw(self, type, value=None, traceback=None):
13676
return self.gen.throw(type, value, traceback)
@@ -202,7 +142,7 @@ def coroutine(func):
202142
If the coroutine is not yielded from before it is destroyed,
203143
an error message is logged.
204144
"""
205-
if _inspect_iscoroutinefunction(func):
145+
if inspect.iscoroutinefunction(func):
206146
# In Python 3.5 that's all we need to do for coroutines
207147
# defined with "async def".
208148
# Wrapping in CoroWrapper will happen via
@@ -218,23 +158,20 @@ def coro(*args, **kw):
218158
if (base_futures.isfuture(res) or inspect.isgenerator(res) or
219159
isinstance(res, CoroWrapper)):
220160
res = yield from res
221-
elif _AwaitableABC is not None:
161+
else:
222162
# If 'func' returns an Awaitable (new in 3.5) we
223163
# want to run it.
224164
try:
225165
await_meth = res.__await__
226166
except AttributeError:
227167
pass
228168
else:
229-
if isinstance(res, _AwaitableABC):
169+
if isinstance(res, Awaitable):
230170
res = yield from await_meth()
231171
return res
232172

233173
if not _DEBUG:
234-
if _types_coroutine is None:
235-
wrapper = coro
236-
else:
237-
wrapper = _types_coroutine(coro)
174+
wrapper = types.coroutine(coro)
238175
else:
239176
@functools.wraps(func)
240177
def wrapper(*args, **kwds):
@@ -259,17 +196,14 @@ def wrapper(*args, **kwds):
259196

260197
def iscoroutinefunction(func):
261198
"""Return True if func is a decorated coroutine function."""
262-
return (getattr(func, '_is_coroutine', None) is _is_coroutine or
263-
_inspect_iscoroutinefunction(func))
199+
return (inspect.iscoroutinefunction(func) or
200+
getattr(func, '_is_coroutine', None) is _is_coroutine)
264201

265202

266-
_COROUTINE_TYPES = (types.GeneratorType, CoroWrapper)
267-
if _CoroutineABC is not None:
268-
_COROUTINE_TYPES += (_CoroutineABC,)
269-
if _types_CoroutineType is not None:
270-
# Prioritize native coroutine check to speed-up
271-
# asyncio.iscoroutine.
272-
_COROUTINE_TYPES = (_types_CoroutineType,) + _COROUTINE_TYPES
203+
# Prioritize native coroutine check to speed-up
204+
# asyncio.iscoroutine.
205+
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
206+
Coroutine, CoroWrapper)
273207

274208

275209
def iscoroutine(obj):

‎Lib/asyncio/unix_events.py‎

Lines changed: 9 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,6 @@ def _sighandler_noop(signum, frame):
3838
pass
3939

4040

41-
try:
42-
_fspath = os.fspath
43-
except AttributeError:
44-
# Python 3.5 or earlier
45-
_fspath = lambda path: path
46-
47-
4841
class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
4942
"""Unix event loop.
5043
@@ -74,7 +67,7 @@ def add_signal_handler(self, sig, callback, *args):
7467
Raise RuntimeError if there is a problem setting up the handler.
7568
"""
7669
if (coroutines.iscoroutine(callback)
77-
or coroutines.iscoroutinefunction(callback)):
70+
or coroutines.iscoroutinefunction(callback)):
7871
raise TypeError("coroutines cannot be used "
7972
"with add_signal_handler()")
8073
self._check_signal(sig)
@@ -226,7 +219,7 @@ def create_unix_connection(self, protocol_factory, path=None, *,
226219
raise ValueError(
227220
'path and sock can not be specified at the same time')
228221

229-
path = _fspath(path)
222+
path = os.fspath(path)
230223
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
231224
try:
232225
sock.setblocking(False)
@@ -260,7 +253,7 @@ def create_unix_server(self, protocol_factory, path=None, *,
260253
raise ValueError(
261254
'path and sock can not be specified at the same time')
262255

263-
path = _fspath(path)
256+
path = os.fspath(path)
264257
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
265258

266259
# Check for abstract socket. `str` and `bytes` paths are supported.
@@ -272,7 +265,8 @@ def create_unix_server(self, protocol_factory, path=None, *,
272265
pass
273266
except OSError as err:
274267
# Directory may have permissions only to create socket.
275-
logger.error('Unable to check or remove stale UNIX socket %r: %r', path, err)
268+
logger.error('Unable to check or remove stale UNIX socket '
269+
'%r: %r', path, err)
276270

277271
try:
278272
sock.bind(path)
@@ -306,18 +300,6 @@ def create_unix_server(self, protocol_factory, path=None, *,
306300
return server
307301

308302

309-
if hasattr(os, 'set_blocking'):
310-
def _set_nonblocking(fd):
311-
os.set_blocking(fd, False)
312-
else:
313-
import fcntl
314-
315-
def _set_nonblocking(fd):
316-
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
317-
flags = flags | os.O_NONBLOCK
318-
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
319-
320-
321303
class _UnixReadPipeTransport(transports.ReadTransport):
322304

323305
max_size = 256 * 1024 # max bytes we read in one event loop iteration
@@ -340,7 +322,7 @@ def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
340322
self._protocol = None
341323
raise ValueError("Pipe transport is for pipes/sockets only.")
342324

343-
_set_nonblocking(self._fileno)
325+
os.set_blocking(self._fileno, False)
344326

345327
self._loop.call_soon(self._protocol.connection_made, self)
346328
# only start reading when connection_made() has been called
@@ -469,7 +451,7 @@ def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
469451
raise ValueError("Pipe transport is only for "
470452
"pipes, sockets and character devices")
471453

472-
_set_nonblocking(self._fileno)
454+
os.set_blocking(self._fileno, False)
473455
self._loop.call_soon(self._protocol.connection_made, self)
474456

475457
# On AIX, the reader trick (to be notified when the read end of the
@@ -648,22 +630,6 @@ def _call_connection_lost(self, exc):
648630
self._loop = None
649631

650632

651-
if hasattr(os, 'set_inheritable'):
652-
# Python 3.4 and newer
653-
_set_inheritable = os.set_inheritable
654-
else:
655-
import fcntl
656-
657-
def _set_inheritable(fd, inheritable):
658-
cloexec_flag = getattr(fcntl, 'FD_CLOEXEC', 1)
659-
660-
old = fcntl.fcntl(fd, fcntl.F_GETFD)
661-
if not inheritable:
662-
fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
663-
else:
664-
fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
665-
666-
667633
class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
668634

669635
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
@@ -675,12 +641,6 @@ def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
675641
# other end). Notably this is needed on AIX, and works
676642
# just fine on other platforms.
677643
stdin, stdin_w = socket.socketpair()
678-
679-
# Mark the write end of the stdin pipe as non-inheritable,
680-
# needed by close_fds=False on Python 3.3 and older
681-
# (Python 3.4 implements the PEP 446, socketpair returns
682-
# non-inheritable sockets)
683-
_set_inheritable(stdin_w.fileno(), False)
684644
self._proc = subprocess.Popen(
685645
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
686646
universal_newlines=False, bufsize=bufsize, **kwargs)
@@ -1035,8 +995,8 @@ def set_event_loop(self, loop):
1035995

1036996
super().set_event_loop(loop)
1037997

1038-
if self._watcher is not None and \
1039-
isinstance(threading.current_thread(), threading._MainThread):
998+
if (self._watcher is not None and
999+
isinstance(threading.current_thread(), threading._MainThread)):
10401000
self._watcher.attach_loop(loop)
10411001

10421002
def get_child_watcher(self):

‎Lib/test/test_asyncio/test_unix_events.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ def setUp(self):
394394
self.pipe = mock.Mock(spec_set=io.RawIOBase)
395395
self.pipe.fileno.return_value = 5
396396

397-
blocking_patcher = mock.patch('asyncio.unix_events._set_nonblocking')
397+
blocking_patcher = mock.patch('os.set_blocking')
398398
blocking_patcher.start()
399399
self.addCleanup(blocking_patcher.stop)
400400

@@ -544,7 +544,7 @@ def setUp(self):
544544
self.pipe = mock.Mock(spec_set=io.RawIOBase)
545545
self.pipe.fileno.return_value = 5
546546

547-
blocking_patcher = mock.patch('asyncio.unix_events._set_nonblocking')
547+
blocking_patcher = mock.patch('os.set_blocking')
548548
blocking_patcher.start()
549549
self.addCleanup(blocking_patcher.stop)
550550

0 commit comments

Comments
 (0)