You could (ab) use decorators for this, I think. The following works, for example:
def execute_with_context_manager(man): def decorator(f): target = man.__enter__() exc = True try: try: f(target) except: exc = False if not man.__exit__(*sys.exc_info()): raise finally: if exc: man.__exit__(None, None, None) return None return decorator @execute_with_context_manager(open("/etc/motd")) def inside(motd_file): for line in motd_file: print line,
(Well, in Python 2.4 file objects, there are no __enter__ and __exit__ methods, but otherwise they work)
The idea is that you replace the string with:
with bar() as foo: do_something_with(foo) do_something_else_with(foo)
with the declared function "declaration" in:
@execute_with_context_manager( bar() ) def dummyname( foo ): do_something_with(foo) do_something_else_with(foo)
but getting the same behavior (do_something _... executable code). Note that the decorator changes the function declaration into an immediate call, which is more than a little evil.
Anthony towns
source share