Alternative to contextlib.nested with variable number of context managers

后端 未结 4 1649
囚心锁ツ
囚心锁ツ 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:37

    import sys
    import contextlib
    
    class nodeA(object):
    
        def __init__(self):
            print( '__init__ nodeA')
    
        def __enter__(self):
            print( '__enter__ nodeA')
    
        def __exit__(self, a, b, c):
            print( '__exit__ nodeA')
    
    class nodeB(object):
    
        def __init__(self):
            print( '__init__ nodeB')
    
        def __enter__(self):
            print( '__enter__ nodeB')
    
        def __exit__(self, a, b, c):
            print( '__exit__ nodeB')
    
    class nodeC(object):
    
        def __init__(self):
            print( '__init__ nodeC')
    
        def __enter__(self):
            print( '__enter__ nodeC')
    
        def __exit__(self, a, b, c):
            print( '__exit__ nodeC')
    
    print( 'Start...')
    
    a = nodeA()
    b = nodeB()
    c = nodeC()
    
    print( 'Python version: %s' % (sys.version))
    
    if sys.version.startswith('2'):
        print('Use python 2!')
        with contextlib.nested(a, b, c):
            print('hallo?')
    
    if sys.version.startswith('3'):
        print('Use python 3!')
        with contextlib.ExitStack() as stack:
            [stack.enter_context(arg) for arg in [a,b,c]]
    
    print('...end!')
    

提交回复
热议问题