How to combine Python context managers in a new function? -


let's have 2 context managers:

@contextmanager def foo():     [...]  @contextmanager def bar():     [...] 

in python 2.7 can use both of them around code block this:

def do_something():     foo(), bar():         [...] 

but how can combine both of them single context manager (for dry/clarity):

@contextmanager def foobar():     [???]  def do_something():     foobar():         [...] 

i don't think can call other 2 context managers , expect work:

@contextmanager def foobar():     # wrong(?)     foo()     bar() 

since context manager have __enter__ , __exit__ called @ points, combine of foo , bar appropriately.

if insist on using contextlib.contextmanager - again, replicate the logic described in docs:

the function being decorated must return generator-iterator when called. iterator must yield 1 value, bound targets in statement’s clause, if any.

at point generator yields, block nested in statement executed. generator resumed after block exited. if unhandled exception occurs in block, reraised inside generator @ point yield occurred. thus, can use try...except...finally statement trap error (if any), or ensure cleanup takes place. if exception trapped merely in order log or perform action (rather suppress entirely), generator must reraise exception. otherwise generator context manager indicate statement exception has been handled, , execution resume statement following statement.

def combined(*ff):     bound_value=tuple(f.next() f in ff)     yield bound_value     f in ff:         try: f.next()         except stopiteration: pass 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -