Alternative to contextlib.nested with variable number of context managers

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

    It's a little vexing that the python3 maintainers chose to break backwards compatibility, since implementing nested in terms of ExitStack is pretty straightforward:

    try:
        from contextlib import nested  # Python 2
    except ImportError:
        from contextlib import ExitStack, contextmanager
    
        @contextmanager
        def nested(*contexts):
            """
            Reimplementation of nested in python 3.
            """
            with ExitStack() as stack:
                for ctx in contexts:
                    stack.enter_context(ctx)
                yield contexts
    

提交回复
热议问题