@@ -607,6 +607,30 @@ def new_event_loop(self):
607607_lock = threading .Lock ()
608608
609609
610+ # A TLS for the running event loop, used by _get_running_loop.
611+ class _RunningLoop (threading .local ):
612+ _loop = None
613+ _running_loop = _RunningLoop ()
614+
615+
616+ def _get_running_loop ():
617+ """Return the running event loop or None.
618+
619+ This is a low-level function intended to be used by event loops.
620+ This function is thread-specific.
621+ """
622+ return _running_loop ._loop
623+
624+
625+ def _set_running_loop (loop ):
626+ """Set the running event loop.
627+
628+ This is a low-level function intended to be used by event loops.
629+ This function is thread-specific.
630+ """
631+ _running_loop ._loop = loop
632+
633+
610634def _init_event_loop_policy ():
611635 global _event_loop_policy
612636 with _lock :
@@ -632,7 +656,17 @@ def set_event_loop_policy(policy):
632656
633657
634658def get_event_loop ():
635- """Equivalent to calling get_event_loop_policy().get_event_loop()."""
659+ """Return an asyncio event loop.
660+
661+ When called from coroutines, this function will always return the
662+ current event loop.
663+
664+ If there is no current event loop set, the function will return
665+ the result of `get_event_loop_policy().get_event_loop()` call.
666+ """
667+ current_loop = _get_running_loop ()
668+ if current_loop is not None :
669+ return current_loop
636670 return get_event_loop_policy ().get_event_loop ()
637671
638672
0 commit comments