Last active
August 10, 2021 17:09
-
-
Save wch/2c6ae55a92317a4948c39649487d759c to your computer and use it in GitHub Desktop.
ContextVars demonstration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Demonstration of using ContextVars instead of global variables. | |
# Set to True for global mode, False for ContextVar mode | |
global_mode = False | |
# With a global variable, the result is: 1 2 3 3 3 3 3 3 3 | |
# With a ContextVar, the result is: 1 2 3 1 2 3 1 2 3 | |
import asyncio | |
import contextvars | |
N = None | |
Nvar = contextvars.ContextVar("my_number_var") | |
async def print_N(): | |
if global_mode: | |
global N | |
print(N, end=" ") | |
else: | |
print(Nvar.get(), end=" ") | |
async def printloop(n): | |
if global_mode: | |
global N | |
N = n | |
else: | |
Nvar.set(str(n)) | |
for i in range(3): | |
await print_N() | |
await asyncio.sleep(0.1) | |
async def main(): | |
await asyncio.gather( | |
printloop(1), | |
printloop(2), | |
printloop(3) | |
) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment