How do I write a null (no-op) contextmanager in Python?

后端 未结 6 827
抹茶落季
抹茶落季 2021-02-01 12:58

Sometimes I need a dummy context manager that does nothing. It can then be used as a stand-in for a more useful, but optional, context manager. For example:

ctx_         


        
6条回答
  •  心在旅途
    2021-02-01 13:28

    A simple solution for Python 3.6 and below, including 2.7:

    from contextlib import contextmanager
    
    @contextmanager
    def nullcontext(enter_result=None):
        yield enter_result
    

    Since Python 3.7 you should use the provided contextlib.nullcontext instead.

提交回复
热议问题