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

Skip to content

Commit abae67e

Browse files
authored
Add asyncio.get_running_loop() function. (#4782)
1 parent 3e97518 commit abae67e

4 files changed

Lines changed: 27 additions & 1 deletion

File tree

Doc/library/asyncio-eventloops.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ the execution of the process.
2525

2626
Equivalent to calling ``get_event_loop_policy().new_event_loop()``.
2727

28+
.. function:: get_running_loop()
29+
30+
Return the running event loop in the current OS thread. If there
31+
is no running event loop a :exc:`RuntimeError` is raised.
32+
33+
.. versionadded:: 3.7
34+
2835

2936
.. _asyncio-event-loops:
3037

Lib/asyncio/events.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
'get_event_loop_policy', 'set_event_loop_policy',
88
'get_event_loop', 'set_event_loop', 'new_event_loop',
99
'get_child_watcher', 'set_child_watcher',
10-
'_set_running_loop', '_get_running_loop',
10+
'_set_running_loop', 'get_running_loop',
11+
'_get_running_loop',
1112
)
1213

1314
import functools
@@ -646,6 +647,17 @@ class _RunningLoop(threading.local):
646647
_running_loop = _RunningLoop()
647648

648649

650+
def get_running_loop():
651+
"""Return the running event loop. Raise a RuntimeError if there is none.
652+
653+
This function is thread-specific.
654+
"""
655+
loop = _get_running_loop()
656+
if loop is None:
657+
raise RuntimeError('no running event loop')
658+
return loop
659+
660+
649661
def _get_running_loop():
650662
"""Return the running event loop or None.
651663

Lib/test/test_asyncio/test_events.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2733,10 +2733,13 @@ def get_event_loop(self):
27332733
try:
27342734
asyncio.set_event_loop_policy(Policy())
27352735
loop = asyncio.new_event_loop()
2736+
with self.assertRaisesRegex(RuntimeError, 'no running'):
2737+
self.assertIs(asyncio.get_running_loop(), None)
27362738
self.assertIs(asyncio._get_running_loop(), None)
27372739

27382740
async def func():
27392741
self.assertIs(asyncio.get_event_loop(), loop)
2742+
self.assertIs(asyncio.get_running_loop(), loop)
27402743
self.assertIs(asyncio._get_running_loop(), loop)
27412744

27422745
loop.run_until_complete(func())
@@ -2745,6 +2748,9 @@ async def func():
27452748
if loop is not None:
27462749
loop.close()
27472750

2751+
with self.assertRaisesRegex(RuntimeError, 'no running'):
2752+
self.assertIs(asyncio.get_running_loop(), None)
2753+
27482754
self.assertIs(asyncio._get_running_loop(), None)
27492755

27502756

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add asyncio.get_running_loop() function.

0 commit comments

Comments
 (0)