Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Doc/library/asyncio-eventloops.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ the execution of the process.

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

.. function:: get_running_loop()

Return the running event loop in the current OS thread. If there
is no running event loop a :exc:`RuntimeError` is raised.

.. versionadded:: 3.7


.. _asyncio-event-loops:

Expand Down
14 changes: 13 additions & 1 deletion Lib/asyncio/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
'get_event_loop_policy', 'set_event_loop_policy',
'get_event_loop', 'set_event_loop', 'new_event_loop',
'get_child_watcher', 'set_child_watcher',
'_set_running_loop', '_get_running_loop',
'_set_running_loop', 'get_running_loop',
'_get_running_loop',
)

import functools
Expand Down Expand Up @@ -646,6 +647,17 @@ class _RunningLoop(threading.local):
_running_loop = _RunningLoop()


def get_running_loop():
"""Return the running event loop. Raise a RuntimeError if there is none.

This function is thread-specific.
"""
loop = _get_running_loop()
if loop is None:
raise RuntimeError('no running event loop')
return loop


def _get_running_loop():
"""Return the running event loop or None.

Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_asyncio/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -2735,10 +2735,13 @@ def get_event_loop(self):
try:
asyncio.set_event_loop_policy(Policy())
loop = asyncio.new_event_loop()
with self.assertRaisesRegex(RuntimeError, 'no running'):
self.assertIs(asyncio.get_running_loop(), None)
self.assertIs(asyncio._get_running_loop(), None)

async def func():
self.assertIs(asyncio.get_event_loop(), loop)
self.assertIs(asyncio.get_running_loop(), loop)
self.assertIs(asyncio._get_running_loop(), loop)

loop.run_until_complete(func())
Expand All @@ -2747,6 +2750,9 @@ async def func():
if loop is not None:
loop.close()

with self.assertRaisesRegex(RuntimeError, 'no running'):
self.assertIs(asyncio.get_running_loop(), None)

self.assertIs(asyncio._get_running_loop(), None)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add asyncio.get_running_loop() function.