Last active
August 16, 2020 00:29
-
-
Save shoyer/a6f977ca4c1a17fe9cb0c8f3af7c762e to your computer and use it in GitHub Desktop.
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
# Copyright 2020 Google LLC. | |
# SPDX-License-Identifier: Apache-2.0 | |
from contextvars import ContextVar | |
from contextlib import contextmanager | |
# library code | |
my_option = ContextVar('my_option', default='default') | |
@contextmanager | |
def my_option_context(value): | |
token = my_option.set(value) | |
yield | |
my_option.reset(token) | |
# example usage | |
assert my_option.get() == 'default' | |
my_option.set('new') | |
assert my_option.get() == 'new' | |
with my_option_context('temporary'): | |
assert my_option.get() == 'temporary' | |
assert my_option.get() == 'new' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment