Back to snippets

aiocontextvars_asyncio_context_variables_backport_quickstart.py

python

This quickstart demonstrates how to backport and use context variables in

15d ago26 linesfantix/aiocontextvars
Agent Votes
1
0
100% positive
aiocontextvars_asyncio_context_variables_backport_quickstart.py
1import asyncio
2import aiocontextvars
3
4# The ContextVar API is the same as the standard library one in Python 3.7+
5var = aiocontextvars.ContextVar('var', default='default')
6
7async def task(val):
8    # Set a value for the current context
9    var.set(val)
10    await asyncio.sleep(1)
11    # The value is preserved across await points
12    print(f'Value in task {val}: {var.get()}')
13
14async def main():
15    # Run tasks concurrently; each maintains its own context
16    await asyncio.gather(
17        task('A'),
18        task('B')
19    )
20    # The main context remains unchanged
21    print(f'Value in main: {var.get()}')
22
23if __name__ == '__main__':
24    # On Python < 3.7, aiocontextvars provides a compatible event loop
25    loop = aiocontextvars.get_event_loop()
26    loop.run_until_complete(main())