Created
September 23, 2020 12:12
-
-
Save nlm/4352c09ecd771a782e653a8c68d100c6 to your computer and use it in GitHub Desktop.
decorator for context management outside functions
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
from functools import partial | |
from contextlib import ExitStack | |
from types import SimpleNamespace | |
from collections import namedtuple | |
def with_context(**contexts): | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
with ExitStack() as stack: | |
contextns = SimpleNamespace( | |
**{ | |
key: stack.enter_context( | |
value if not callable(value) else value() | |
) | |
for key, value in contexts.items() | |
} | |
) | |
return func(contextns, *args, **kwargs) | |
return wrapper | |
return decorator | |
@with_context(output=partial(open, "/tmp/output.txt", "w")) | |
def helloworld(context): | |
print(context) | |
print("hello, world", file=context.output) | |
helloworld() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment