Azure / msrest-for-python

The runtime library "msrest" for AutoRest generated Python clients.
MIT License
41 stars 64 forks source link

Get running loop asyncio #136

Closed lmazuel closed 4 years ago

lmazuel commented 5 years ago

After some digging:

def get_running_loop():
    try:
        return asyncio.get_running_loop()
    except AttributeError:  # 3.5 / 3.6
        loop = asyncio._get_running_loop()
        if loop is None:
            raise RuntimeError('no running event loop')
        return loop

Ref: https://github.com/python/cpython/blob/a234e148394c2c7419372ab65b773d53a57f3625/Lib/asyncio/events.py#L674-L683 And doc: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop

Because this function has rather complex behavior (especially when custom event loop policies are in use), using the get_running_loop() function is preferred to get_event_loop() in coroutines and callbacks.

lmazuel commented 5 years ago

@johanste @annatisch

annatisch commented 5 years ago

This is what we used elsewhere as an interim measure until we could do a major version bump. We found too many people were broken by simply raising a RuntimeError, as they weren't managing their event loops.

This code also accommodates Python v3.5.0-3.5.2. We don't support these versions, and people shouldn't be using them - it's likely that the SDK will break elsewhere anyway. But at least it wont break here :)

def get_running_loop():
    try:
        return asyncio.get_running_loop()
    except AttributeError:  # 3.5 / 3.6
        loop = None
        try:
            loop = asyncio._get_running_loop()  # pylint: disable=protected-access
        except AttributeError:
            # Running deprecated Python v3.5.0-2
            logger.warning('This version of Python is deprecated, please upgrade to >= v3.5.3')
        if loop is None:
            logger.warning('No running event loop')
            loop = asyncio.get_event_loop()
        return loop
    except RuntimeError:
        # For backwards compatibility, create new event loop
        logger.warning('No running event loop')
        return asyncio.get_event_loop()
lmazuel commented 4 years ago

AIO support in msrest was experimental, this problem is fixed in azure-core