Skip to content

Instantly share code, notes, and snippets.

@maxfischer2781
Created September 19, 2019 15:56
Show Gist options
  • Save maxfischer2781/b61e862cb74b8ab948d83d9d79e6b507 to your computer and use it in GitHub Desktop.
Save maxfischer2781/b61e862cb74b8ab948d83d9d79e6b507 to your computer and use it in GitHub Desktop.
Python context manager that is stack-aware in a thread safe manner
import threading, random
class StackContext:
def __init__(self):
self._state = threading.local()
self._state.stack = []
def __enter__(self):
this_context = random.random()
self._state.stack.append(this_context)
print('enter', this_context)
return this_context
def __exit__(self, *args):
this_context = self._state.stack.pop(-1)
print('exit', this_context)
context = StackContext()
with context:
with context:
with context as inner:
print(f'inner={inner}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment