Created
February 24, 2020 09:26
-
-
Save opethe1st/ced26d5a733e6dc10506c87b3f78cccd to your computer and use it in GitHub Desktop.
A context manager for managing contextvars
This file contains 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
import contextlib | |
import contextvars | |
@contextlib.contextmanager | |
def context(contextvar: contextvars.ContextVar, value): | |
token = contextvar.set(value) | |
yield | |
contextvar.reset(token) |
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
Thanks for sharing! In my case, I needed to make sure that the contextvar was reset even if the
yield
ed portion raised an exception. This is what I did to handle that case, in case it helps anyone who comes across this example.