◐ Shell
clean mode source ↗

bpo-38599: Deprecate creation of asyncio object when the loop is not running by eamanu · Pull Request #18195 · python/cpython

def __init__(self, loop=None):
    if loop is None:
        loop = asyncio._get_running_loop()
        if loop is None:
            # issue warning
            loop = asyncio.get_event_loop()

Ah, I see. That's likely the most explicit way to always raise when the constructor for the class is called outside of a coroutine, while also not having a second redundant deprecation warning from passing an explicit loop argument. With the current implementation in the PR, it can raise both deprecation warnings at the same time.

Out of curiosity though, would something like this work as well, or is there a situation it wouldn't appropriately cover as well as the above?:

def __init__(self, loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()
        if not loop.is_running():
            # warn
            ...

Although it's not a significant concern since this is within the internals of asyncio, I typically prefer to avoid directly accessing private members of other classes when possible. IMO, it also makes the code a bit more obvious to readers since they're less likely to be as familiar with _get_running_loop().

I suspect that you may have been considering the discussion about eventually deprecating asyncio.get_event_loop(), meaning this would have to be changed (unlike your example), but I wanted to make sure that I was understanding the motivations correctly.