Skip to content

Instantly share code, notes, and snippets.

@michael-lazar
Last active August 29, 2015 14:15
Show Gist options
  • Save michael-lazar/862e368a2e76ffe60854 to your computer and use it in GitHub Desktop.
Save michael-lazar/862e368a2e76ffe60854 to your computer and use it in GitHub Desktop.
Map function for nesting with statements
from contextlib import contextmanager
from copy import copy
@contextmanager
def map_with(funcs, args, init=True):
if init:
funcs, args = copy(funcs), copy(args)
if len(funcs) == 0:
yield []
else:
func, arg = funcs.pop(), args.pop()
with func(arg) as f:
with map_with(funcs, args, False) as out:
yield out + [f]
@contextmanager
def func(val):
print 'entering {}'.format(val)
yield val
print 'exiting {}'.format(val)
if __name__ == '__main__':
funcs = [func] * 10
args = range(10)
with map_with(funcs, args) as out:
print out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment