Skip to content

Commit cb5926e

Browse files
kumaraditya303picnixz
authored andcommitted
pythongh-126353: remove implicit creation of loop from asyncio.get_event_loop (python#126354)
Remove implicit creation of loop from `asyncio.get_event_loop`. This is a step forward of deprecating the policy system of asyncio.
1 parent a5616e5 commit cb5926e

File tree

8 files changed

+24
-62
lines changed

8 files changed

+24
-62
lines changed

Doc/library/asyncio-eventloop.rst

+2-3
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,8 @@ an event loop:
5959
instead of using these lower level functions to manually create and close an
6060
event loop.
6161

62-
.. deprecated:: 3.12
63-
Deprecation warning is emitted if there is no current event loop.
64-
In some future Python release this will become an error.
62+
.. versionchanged:: 3.14
63+
Raises a :exc:`RuntimeError` if there is no current event loop.
6564

6665
.. function:: set_event_loop(loop)
6766

Doc/library/asyncio-policy.rst

+3-5
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,9 @@ asyncio ships with the following built-in policies:
9797

9898
On Windows, :class:`ProactorEventLoop` is now used by default.
9999

100-
.. deprecated:: 3.12
101-
The :meth:`get_event_loop` method of the default asyncio policy now emits
102-
a :exc:`DeprecationWarning` if there is no current event loop set and it
103-
decides to create one.
104-
In some future Python release this will become an error.
100+
.. versionchanged:: 3.14
101+
The :meth:`get_event_loop` method of the default asyncio policy now
102+
raises a :exc:`RuntimeError` if there is no set event loop.
105103

106104

107105
.. class:: WindowsSelectorEventLoopPolicy

Doc/whatsnew/3.14.rst

+5
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,11 @@ asyncio
576576

577577
(Contributed by Kumar Aditya in :gh:`120804`.)
578578

579+
* Removed implicit creation of event loop by :func:`asyncio.get_event_loop`.
580+
It now raises a :exc:`RuntimeError` if there is no current event loop.
581+
(Contributed by Kumar Aditya in :gh:`126353`.)
582+
583+
579584
collections.abc
580585
---------------
581586

Lib/asyncio/events.py

-24
Original file line numberDiff line numberDiff line change
@@ -668,7 +668,6 @@ class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
668668

669669
class _Local(threading.local):
670670
_loop = None
671-
_set_called = False
672671

673672
def __init__(self):
674673
self._local = self._Local()
@@ -678,28 +677,6 @@ def get_event_loop(self):
678677
679678
Returns an instance of EventLoop or raises an exception.
680679
"""
681-
if (self._local._loop is None and
682-
not self._local._set_called and
683-
threading.current_thread() is threading.main_thread()):
684-
stacklevel = 2
685-
try:
686-
f = sys._getframe(1)
687-
except AttributeError:
688-
pass
689-
else:
690-
# Move up the call stack so that the warning is attached
691-
# to the line outside asyncio itself.
692-
while f:
693-
module = f.f_globals.get('__name__')
694-
if not (module == 'asyncio' or module.startswith('asyncio.')):
695-
break
696-
f = f.f_back
697-
stacklevel += 1
698-
import warnings
699-
warnings.warn('There is no current event loop',
700-
DeprecationWarning, stacklevel=stacklevel)
701-
self.set_event_loop(self.new_event_loop())
702-
703680
if self._local._loop is None:
704681
raise RuntimeError('There is no current event loop in thread %r.'
705682
% threading.current_thread().name)
@@ -708,7 +685,6 @@ def get_event_loop(self):
708685

709686
def set_event_loop(self, loop):
710687
"""Set the event loop."""
711-
self._local._set_called = True
712688
if loop is not None and not isinstance(loop, AbstractEventLoop):
713689
raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
714690
self._local._loop = loop

Lib/test/test_asyncio/test_events.py

+9-25
Original file line numberDiff line numberDiff line change
@@ -2704,33 +2704,22 @@ def test_event_loop_policy(self):
27042704
def test_get_event_loop(self):
27052705
policy = asyncio.DefaultEventLoopPolicy()
27062706
self.assertIsNone(policy._local._loop)
2707-
with self.assertWarns(DeprecationWarning) as cm:
2708-
loop = policy.get_event_loop()
2709-
self.assertEqual(cm.filename, __file__)
2710-
self.assertIsInstance(loop, asyncio.AbstractEventLoop)
27112707

2712-
self.assertIs(policy._local._loop, loop)
2713-
self.assertIs(loop, policy.get_event_loop())
2714-
loop.close()
2708+
with self.assertRaises(RuntimeError):
2709+
loop = policy.get_event_loop()
2710+
self.assertIsNone(policy._local._loop)
27152711

2716-
def test_get_event_loop_calls_set_event_loop(self):
2712+
def test_get_event_loop_does_not_call_set_event_loop(self):
27172713
policy = asyncio.DefaultEventLoopPolicy()
27182714

27192715
with mock.patch.object(
27202716
policy, "set_event_loop",
27212717
wraps=policy.set_event_loop) as m_set_event_loop:
27222718

2723-
with self.assertWarns(DeprecationWarning) as cm:
2719+
with self.assertRaises(RuntimeError):
27242720
loop = policy.get_event_loop()
2725-
self.addCleanup(loop.close)
2726-
self.assertEqual(cm.filename, __file__)
27272721

2728-
# policy._local._loop must be set through .set_event_loop()
2729-
# (the unix DefaultEventLoopPolicy needs this call to attach
2730-
# the child watcher correctly)
2731-
m_set_event_loop.assert_called_with(loop)
2732-
2733-
loop.close()
2722+
m_set_event_loop.assert_not_called()
27342723

27352724
def test_get_event_loop_after_set_none(self):
27362725
policy = asyncio.DefaultEventLoopPolicy()
@@ -2912,17 +2901,12 @@ def test_get_event_loop_returns_running_loop2(self):
29122901
loop = asyncio.new_event_loop()
29132902
self.addCleanup(loop.close)
29142903

2915-
with self.assertWarns(DeprecationWarning) as cm:
2916-
loop2 = asyncio.get_event_loop()
2917-
self.addCleanup(loop2.close)
2918-
self.assertEqual(cm.filename, __file__)
2919-
asyncio.set_event_loop(None)
29202904
with self.assertRaisesRegex(RuntimeError, 'no current'):
29212905
asyncio.get_event_loop()
29222906

2923-
with self.assertRaisesRegex(RuntimeError, 'no running'):
2924-
asyncio.get_running_loop()
2925-
self.assertIs(asyncio._get_running_loop(), None)
2907+
asyncio.set_event_loop(None)
2908+
with self.assertRaisesRegex(RuntimeError, 'no current'):
2909+
asyncio.get_event_loop()
29262910

29272911
async def func():
29282912
self.assertIs(asyncio.get_event_loop(), loop)

Lib/test/test_asyncio/test_unix_events.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1195,8 +1195,7 @@ async def test_fork_not_share_event_loop(self):
11951195
if pid == 0:
11961196
# child
11971197
try:
1198-
with self.assertWarns(DeprecationWarning):
1199-
loop = asyncio.get_event_loop_policy().get_event_loop()
1198+
loop = asyncio.get_event_loop()
12001199
os.write(w, b'LOOP:' + str(id(loop)).encode())
12011200
except RuntimeError:
12021201
os.write(w, b'NO LOOP')
@@ -1207,8 +1206,7 @@ async def test_fork_not_share_event_loop(self):
12071206
else:
12081207
# parent
12091208
result = os.read(r, 100)
1210-
self.assertEqual(result[:5], b'LOOP:', result)
1211-
self.assertNotEqual(int(result[5:]), id(loop))
1209+
self.assertEqual(result, b'NO LOOP')
12121210
wait_process(pid, exitcode=0)
12131211

12141212
@hashlib_helper.requires_hashdigest('md5')

Lib/test/test_cmd_line.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -924,7 +924,7 @@ def test_python_gil(self):
924924
self.assertEqual(proc.stderr, '')
925925

926926
def test_python_asyncio_debug(self):
927-
code = "import asyncio; print(asyncio.get_event_loop().get_debug())"
927+
code = "import asyncio; print(asyncio.new_event_loop().get_debug())"
928928
rc, out, err = assert_python_ok('-c', code, PYTHONASYNCIODEBUG='1')
929929
self.assertIn(b'True', out)
930930

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`asyncio.get_event_loop` now does not implicitly creates an event loop.
2+
It now raises a :exc:`RuntimeError` if there is no set event loop. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)