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

asyncio context propagation in Python 3.5/3.6 #71

Closed
a-feld opened this issue Aug 1, 2019 · 3 comments
Closed

asyncio context propagation in Python 3.5/3.6 #71

a-feld opened this issue Aug 1, 2019 · 3 comments
Assignees
Labels
api Affects the API package.

Comments

@a-feld
Copy link
Member

a-feld commented Aug 1, 2019

The contextvars approach to context propagation requires copying current context on asyncio task creation. This is done internally in asyncio for Python 3.7; however, on Python <3.7 context is not propagated automatically.

Example:

import asyncio
import contextvars

current_task = contextvars.ContextVar("current_task")


async def foo(foo_started, bar_done):
    current_task.set("foo")
    foo_started.set()
    await bar_done.wait()
    print("foo task:", current_task.get())


async def bar(foo_started, bar_done):
    await foo_started.wait()
    current_task.set("bar")
    bar_done.set()


async def main():
    foo_started = asyncio.Event()
    bar_done = asyncio.Event()

    await asyncio.gather(
        foo(foo_started, bar_done),
        bar(foo_started, bar_done),
    )


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

In Python 3.7, the code above will print foo task: foo
In Python 3.5 and 3.6, the code above will print foo task: bar

@toumorokoshi
Copy link
Member

I've used https://github.com/Skyscanner/aiotask-context before this functionality existed natively.

@reyang reyang self-assigned this Aug 16, 2019
@condorcet
Copy link

Hi there! The alternative is to use contextvars backport -- aiocontextvars https://github.com/fantix/aiocontextvars/
But it has some limitations:

As I understand aiotask-context has the same problems especially the last one. Big advantage of aiocontextvars is drop-in replacement original context without code modification.

@Oberon00 Oberon00 added the api Affects the API package. label Sep 24, 2019
@mauriciovasquezbernal
Copy link
Member

@codeboten was it solved by #395?

@c24t c24t closed this as completed Apr 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Affects the API package.
Projects
None yet
Development

No branches or pull requests

7 participants