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

后端 未结 6 889
抹茶落季
抹茶落季 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:30

    For Python 2.7+ , you can use

    import contextlib
    with (lambda noop_func: contextlib.contextmanager(noop_func))(lambda: (yield))():
        print("hi")
    

提交回复
热议问题