Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Monkeypatching of loop functions doesn't cover all cases #83

Open
oremanj opened this issue May 26, 2020 · 0 comments
Open

Monkeypatching of loop functions doesn't cover all cases #83

oremanj opened this issue May 26, 2020 · 0 comments

Comments

@oremanj
Copy link
Member

oremanj commented May 26, 2020

A user on Gitter discovered that this simple-seeming code doesn't work:

from asyncio import get_running_loop
from trio import run
from trio_asyncio import aio_as_trio, open_loop

async def main():
    async def inner():
        return get_running_loop()

    async with open_loop():
        print(await aio_as_trio(inner)())

run(main)

There are two issues here:

  • If you import individual names from asyncio before importing trio-asyncio, you won't see the monkeypatched versions. This is relevant in practice because of the stylistic convention to put stdlib imports before third-party imports. We can fix this for functions whose originals are defined in Python by changing the __code__ on the same function object, rather than changing which function object the module refers to. For functions defined in C, we can't do that, but we might be able to do something like check sys.getrefcount() of the originals and warn if it's higher than what you get from just import asyncio.
  • We aren't updating asyncio.get_running_loop or asyncio._get_running_loop from our monkeypatching; we're only updating the references in asyncio.events. This is just an oversight and can easily be fixed. The result is that asyncio internally sees our monkeypatch but users who directly call get_running_loop don't.
vcalvert added a commit to vcalvert/aioredis that referenced this issue Oct 21, 2020
The old code would use `get_running_loop()` preferentially if available, which
results in a "No running loop" error, even if `trio-asyncio` has an open loop.

Specifically, this is noted in an existing `trio-asyncio` issue:
python-trio/trio-asyncio#83

It may be possible to use `aioredis==1.3.1` and just ensure it is imported
_after_ `trio-asyncio`, in which case the `trio-asyncio` monkeypatching should
work.
niklasf added a commit to niklasf/trio-asyncio that referenced this issue Jan 5, 2021
niklasf added a commit to niklasf/trio-asyncio that referenced this issue Jan 6, 2021
oremanj added a commit that referenced this issue Jan 7, 2021
Fix asyncio.get_running_loop() monkey-patching (#83)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant