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

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

    Since Python 3.2, memoryview(b'') can be use as a no-op context manager. See https://docs.python.org/3/library/stdtypes.html#memoryview.release.

    Pros

    • No imports required

    • Works on 3.2+

    • Roughly twice as fast as contextlib.nullcontext

    Cons

    • You probably want to add a # no-op comment.

提交回复
热议问题