Last active
August 29, 2015 14:15
-
-
Save michael-lazar/862e368a2e76ffe60854 to your computer and use it in GitHub Desktop.
Map function for nesting with statements
This file contains 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 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