Skip to content

Instantly share code, notes, and snippets.

@sbutler
Last active August 29, 2015 14:21
Show Gist options
  • Save sbutler/5157265aa97bba665349 to your computer and use it in GitHub Desktop.
Save sbutler/5157265aa97bba665349 to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
import threading
class _Local(threading.local):
def __init__(self):
self.ctxt = {}
_data = _Local()
@contextmanager
def setctxt(**kwargs):
"""
Context manager that sets some keys/values for the duration
of the block and then unsets them when it is finished.
with setctxt(foo='abc', bar='123'):
do_code()
"""
saved = _data.ctxt.copy()
_data.ctxt.update(kwargs)
try:
yield
finally:
_data.ctxt = saved
def getctxt(key, default=None):
"""
Gets the context value by key, or None if it was not set.
value = getctxt('foo')
"""
return _data.ctxt.get(key, default)
def hasctxt(key):
""" Returns true if the context has a value set (even if it is None). """
return key in _data.ctxt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment