Created
September 19, 2019 15:56
-
-
Save maxfischer2781/b61e862cb74b8ab948d83d9d79e6b507 to your computer and use it in GitHub Desktop.
Python context manager that is stack-aware in a thread safe manner
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
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