Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python enter_context
"""Imperative enter/exit control for python contextmanagers.
Where you'd prefer to use `with`:
with my_context(123) as f:
do_something()
but only have access to before and after hook-functions (as with Flask):
def before_hook():
pass # Enter the context.
def after_hook():
pass # Exit the context.
def handler():
return do_something()
you can use the `enter_context` function as an open/close pair of functions:
ctxt = threading.local()
def before_hook():
f, ctxt.close_context = enter_context(my_context, 123)
def after_hook():
ctxt.close_context()
def handler():
return do_something()
"""
from contextlib import contextmanager
from functools import partial
def main():
with context(123) as mgr:
print "middle: %r" % (mgr,)
print "---"
mgr, exit_context = enter_context(context, 456)
print "middle: %r" % (mgr,)
exit_context()
@contextmanager
def context(*args, **kwargs):
print "in"
yield {'args': args, 'kwargs': kwargs}
print "out"
def enter_context(func, *args, **kwargs):
def enter():
with func(*args, **kwargs) as f:
yield f
e = enter()
def exit():
try:
next(e)
except StopIteration:
pass
return next(e), exit
if __name__ == "__main__":
main()
@icio

This comment has been minimized.

Copy link
Owner Author

commented Jan 6, 2016

$ python context_faker.py
in
middle: {'args': (123,), 'kwargs': {}}
out

---
in
middle: {'args': (456,), 'kwargs': {}}
out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.