Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e5bd5ad

Browse files
gh-100160: Restore and deprecate implicit creation of an event loop (GH-100410)
Partially revert changes made in GH-93453. asyncio.DefaultEventLoopPolicy.get_event_loop() now emits a DeprecationWarning and creates and sets a new event loop instead of raising a RuntimeError if there is no current event loop set. Co-authored-by: Guido van Rossum <[email protected]>
1 parent 468c3bf commit e5bd5ad

File tree

8 files changed

+77
-41
lines changed

8 files changed

+77
-41
lines changed

Doc/library/asyncio-eventloop.rst

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ an event loop:
4848
running event loop.
4949

5050
If there is no running event loop set, the function will return
51-
the result of calling ``get_event_loop_policy().get_event_loop()``.
51+
the result of the ``get_event_loop_policy().get_event_loop()`` call.
5252

5353
Because this function has rather complex behavior (especially
5454
when custom event loop policies are in use), using the
@@ -59,11 +59,9 @@ an event loop:
5959
instead of using these lower level functions to manually create and close an
6060
event loop.
6161

62-
.. note::
63-
In Python versions 3.10.0--3.10.8 and 3.11.0 this function
64-
(and other functions which used it implicitly) emitted a
65-
:exc:`DeprecationWarning` if there was no running event loop, even if
66-
the current loop was set.
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.
6765

6866
.. function:: set_event_loop(loop)
6967

Doc/library/asyncio-policy.rst

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,11 @@ asyncio ships with the following built-in policies:
116116

117117
On Windows, :class:`ProactorEventLoop` is now used by default.
118118

119-
.. versionchanged:: 3.12
120-
:meth:`get_event_loop` now raises a :exc:`RuntimeError` if there is no
121-
current event loop set.
119+
.. deprecated:: 3.12
120+
The :meth:`get_event_loop` method of the default asyncio policy now emits
121+
a :exc:`DeprecationWarning` if there is no current event loop set and it
122+
decides to create one.
123+
In some future Python release this will become an error.
122124

123125

124126
.. class:: WindowsSelectorEventLoopPolicy

Doc/whatsnew/3.10.rst

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1709,19 +1709,6 @@ Deprecated
17091709
scheduled for removal in Python 3.12.
17101710
(Contributed by Erlend E. Aasland in :issue:`42264`.)
17111711
1712-
* :func:`asyncio.get_event_loop` now emits a deprecation warning if there is
1713-
no running event loop. In the future it will be an alias of
1714-
:func:`~asyncio.get_running_loop`.
1715-
:mod:`asyncio` functions which implicitly create :class:`~asyncio.Future`
1716-
or :class:`~asyncio.Task` objects now emit
1717-
a deprecation warning if there is no running event loop and no explicit
1718-
*loop* argument is passed: :func:`~asyncio.ensure_future`,
1719-
:func:`~asyncio.wrap_future`, :func:`~asyncio.gather`,
1720-
:func:`~asyncio.shield`, :func:`~asyncio.as_completed` and constructors of
1721-
:class:`~asyncio.Future`, :class:`~asyncio.Task`,
1722-
:class:`~asyncio.StreamReader`, :class:`~asyncio.StreamReaderProtocol`.
1723-
(Contributed by Serhiy Storchaka in :issue:`39529`.)
1724-
17251712
* The undocumented built-in function ``sqlite3.enable_shared_cache`` is now
17261713
deprecated, scheduled for removal in Python 3.12. Its use is strongly
17271714
discouraged by the SQLite3 documentation. See `the SQLite3 docs

Doc/whatsnew/3.12.rst

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,11 @@ Deprecated
408408
:exc:`ImportWarning`).
409409
(Contributed by Brett Cannon in :gh:`65961`.)
410410

411+
* The :meth:`~asyncio.DefaultEventLoopPolicy.get_event_loop` method of the
412+
default event loop policy now emits a :exc:`DeprecationWarning` if there
413+
is no current event loop set and it decides to create one.
414+
(Contributed by Serhiy Storchaka and Guido van Rossum in :gh:`100160`.)
415+
411416

412417
Pending Removal in Python 3.13
413418
------------------------------
@@ -710,18 +715,6 @@ Changes in the Python API
710715
around process-global resources, which are best managed from the main interpreter.
711716
(Contributed by Dong-hee Na in :gh:`99127`.)
712717

713-
* :func:`asyncio.get_event_loop` and many other :mod:`asyncio` functions like
714-
:func:`~asyncio.ensure_future`, :func:`~asyncio.shield` or
715-
:func:`~asyncio.gather`, and also the
716-
:meth:`~asyncio.BaseDefaultEventLoopPolicy.get_event_loop` method of
717-
:class:`~asyncio.BaseDefaultEventLoopPolicy` now raise a :exc:`RuntimeError`
718-
if called when there is no running event loop and the current event loop was
719-
not set.
720-
Previously they implicitly created and set a new current event loop.
721-
:exc:`DeprecationWarning` is no longer emitted if there is no running
722-
event loop but the current event loop is set in the policy.
723-
(Contributed by Serhiy Storchaka in :gh:`93453`.)
724-
725718

726719
Build Changes
727720
=============

Lib/asyncio/events.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ def get_event_loop(self):
619619
620620
Returns an event loop object implementing the BaseEventLoop interface,
621621
or raises an exception in case no event loop has been set for the
622-
current context.
622+
current context and the current policy does not specify to create one.
623623
624624
It should never return None."""
625625
raise NotImplementedError
@@ -672,6 +672,28 @@ def get_event_loop(self):
672672
673673
Returns an instance of EventLoop or raises an exception.
674674
"""
675+
if (self._local._loop is None and
676+
not self._local._set_called and
677+
threading.current_thread() is threading.main_thread()):
678+
stacklevel = 2
679+
try:
680+
f = sys._getframe(1)
681+
except AttributeError:
682+
pass
683+
else:
684+
# Move up the call stack so that the warning is attached
685+
# to the line outside asyncio itself.
686+
while f:
687+
module = f.f_globals.get('__name__')
688+
if not (module == 'asyncio' or module.startswith('asyncio.')):
689+
break
690+
f = f.f_back
691+
stacklevel += 1
692+
import warnings
693+
warnings.warn('There is no current event loop',
694+
DeprecationWarning, stacklevel=stacklevel)
695+
self.set_event_loop(self.new_event_loop())
696+
675697
if self._local._loop is None:
676698
raise RuntimeError('There is no current event loop in thread %r.'
677699
% threading.current_thread().name)

Lib/test/test_asyncio/test_events.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2614,8 +2614,33 @@ def test_event_loop_policy(self):
26142614
def test_get_event_loop(self):
26152615
policy = asyncio.DefaultEventLoopPolicy()
26162616
self.assertIsNone(policy._local._loop)
2617-
with self.assertRaisesRegex(RuntimeError, 'no current event loop'):
2618-
policy.get_event_loop()
2617+
with self.assertWarns(DeprecationWarning) as cm:
2618+
loop = policy.get_event_loop()
2619+
self.assertEqual(cm.filename, __file__)
2620+
self.assertIsInstance(loop, asyncio.AbstractEventLoop)
2621+
2622+
self.assertIs(policy._local._loop, loop)
2623+
self.assertIs(loop, policy.get_event_loop())
2624+
loop.close()
2625+
2626+
def test_get_event_loop_calls_set_event_loop(self):
2627+
policy = asyncio.DefaultEventLoopPolicy()
2628+
2629+
with mock.patch.object(
2630+
policy, "set_event_loop",
2631+
wraps=policy.set_event_loop) as m_set_event_loop:
2632+
2633+
with self.assertWarns(DeprecationWarning) as cm:
2634+
loop = policy.get_event_loop()
2635+
self.addCleanup(loop.close)
2636+
self.assertEqual(cm.filename, __file__)
2637+
2638+
# policy._local._loop must be set through .set_event_loop()
2639+
# (the unix DefaultEventLoopPolicy needs this call to attach
2640+
# the child watcher correctly)
2641+
m_set_event_loop.assert_called_with(loop)
2642+
2643+
loop.close()
26192644

26202645
def test_get_event_loop_after_set_none(self):
26212646
policy = asyncio.DefaultEventLoopPolicy()
@@ -2801,8 +2826,10 @@ def test_get_event_loop_returns_running_loop2(self):
28012826
loop = asyncio.new_event_loop()
28022827
self.addCleanup(loop.close)
28032828

2804-
with self.assertRaisesRegex(RuntimeError, 'no current'):
2805-
asyncio.get_event_loop()
2829+
with self.assertWarns(DeprecationWarning) as cm:
2830+
loop2 = asyncio.get_event_loop()
2831+
self.addCleanup(loop2.close)
2832+
self.assertEqual(cm.filename, __file__)
28062833
asyncio.set_event_loop(None)
28072834
with self.assertRaisesRegex(RuntimeError, 'no current'):
28082835
asyncio.get_event_loop()

Lib/test/test_asyncio/test_unix_events.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1884,7 +1884,9 @@ async def test_fork_not_share_event_loop(self):
18841884
if pid == 0:
18851885
# child
18861886
try:
1887-
loop = asyncio.get_event_loop_policy().get_event_loop()
1887+
with self.assertWarns(DeprecationWarning):
1888+
loop = asyncio.get_event_loop_policy().get_event_loop()
1889+
os.write(w, b'LOOP:' + str(id(loop)).encode())
18881890
except RuntimeError:
18891891
os.write(w, b'NO LOOP')
18901892
except:
@@ -1893,7 +1895,9 @@ async def test_fork_not_share_event_loop(self):
18931895
os._exit(0)
18941896
else:
18951897
# parent
1896-
self.assertEqual(os.read(r, 100), b'NO LOOP')
1898+
result = os.read(r, 100)
1899+
self.assertEqual(result[:5], b'LOOP:', result)
1900+
self.assertNotEqual(int(result[5:]), id(loop))
18971901
wait_process(pid, exitcode=0)
18981902

18991903
@hashlib_helper.requires_hashdigest('md5')
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Emit a deprecation warning in
2+
:meth:`asyncio.DefaultEventLoopPolicy.get_event_loop` if there is no current
3+
event loop set and it decides to create one.

0 commit comments

Comments
 (0)