Skip to content

Instantly share code, notes, and snippets.

@nlm
Created September 23, 2020 12:12
Show Gist options
  • Save nlm/4352c09ecd771a782e653a8c68d100c6 to your computer and use it in GitHub Desktop.
Save nlm/4352c09ecd771a782e653a8c68d100c6 to your computer and use it in GitHub Desktop.
decorator for context management outside functions
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