Skip to content
Merged
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
22 changes: 19 additions & 3 deletions maas/client/utils/maas_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,27 @@

__all__ = ["asynchronous", "Asynchronous", "is_loop_running"]

from asyncio import get_event_loop
from asyncio import get_event_loop, new_event_loop, set_event_loop
from functools import wraps
from inspect import isawaitable, iscoroutinefunction


def _get_or_create_event_loop():
"""Return the current event-loop, creating one if necessary.

Python 3.14 removed the implicit creation of an event-loop in the main
thread, so `get_event_loop()` raises `RuntimeError` when no loop has been
set. Fall back to creating and setting a new loop, matching the previous
behaviour on older Python versions.
"""
try:
return get_event_loop()
except RuntimeError:
eventloop = new_event_loop()
set_event_loop(eventloop)
return eventloop


def asynchronous(func):
"""Return `func` in a "smart" asynchronous-aware wrapper.

Expand All @@ -36,7 +52,7 @@ def asynchronous(func):

@wraps(func)
def wrapper(*args, **kwargs):
eventloop = get_event_loop()
eventloop = _get_or_create_event_loop()
result = func(*args, **kwargs)
if not eventloop.is_running():
while isawaitable(result):
Expand Down Expand Up @@ -74,4 +90,4 @@ def is_loop_running():

Then we don't want to block, do we?
"""
return get_event_loop().is_running()
return _get_or_create_event_loop().is_running()
Loading