Skip to content

Instantly share code, notes, and snippets.

@opethe1st
Created February 24, 2020 09:26
Show Gist options
  • Save opethe1st/ced26d5a733e6dc10506c87b3f78cccd to your computer and use it in GitHub Desktop.
Save opethe1st/ced26d5a733e6dc10506c87b3f78cccd to your computer and use it in GitHub Desktop.
A context manager for managing contextvars
import contextlib
import contextvars
@contextlib.contextmanager
def context(contextvar: contextvars.ContextVar, value):
token = contextvar.set(value)
yield
contextvar.reset(token)
@nick-merrill
Copy link

Thanks for sharing! In my case, I needed to make sure that the contextvar was reset even if the yielded portion raised an exception. This is what I did to handle that case, in case it helps anyone who comes across this example.

token = contextvar.set(value)
try:
	yield
finally:
	contextvar.reset(token)

@opethe1st
Copy link
Author

Glad to know you found this useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment