Skip to content

Instantly share code, notes, and snippets.

@shoyer
Last active August 16, 2020 00:29
Show Gist options
  • Save shoyer/a6f977ca4c1a17fe9cb0c8f3af7c762e to your computer and use it in GitHub Desktop.
Save shoyer/a6f977ca4c1a17fe9cb0c8f3af7c762e to your computer and use it in GitHub Desktop.
# 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