Skip to content

Instantly share code, notes, and snippets.

@wch
Last active August 10, 2021 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/2c6ae55a92317a4948c39649487d759c to your computer and use it in GitHub Desktop.
Save wch/2c6ae55a92317a4948c39649487d759c to your computer and use it in GitHub Desktop.
ContextVars demonstration
# 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