Alternative to contextlib.nested with variable number of context managers

后端 未结 4 1641
囚心锁ツ
囚心锁ツ 2020-12-03 10:07

We have code that invokes a variable number of context managers depending on runtime parameters:

from contextlib import nested, contextmanager

@contextmanag         


        
4条回答
  •  独厮守ぢ
    2020-12-03 10:29

    It seems that you are supposed to use the with statement with multiple context manager instances.

    from https://pymotw.com/2/contextlib/:

    In Python 2.7 and later, nested() is deprecated because the with statement supports nesting directly.

    import contextlib
    
    @contextlib.contextmanager
    def make_context(name):
        print 'entering:', name
        yield name
        print 'exiting :', name
    
    with make_context('A') as A, make_context('B') as B, make_context('C') as C:
        print 'inside with statement:', A, B, C
    

提交回复
热议问题