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

Discussão em 'Python' iniciado por Stack, Fevereiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    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_mgr = <meaningfulContextManager> if <condition> else <nullContextManager>
    with ctx_mgr:
    ...


    How do I define such a trivial, empty context manager? Does the Python library offer one off the shelf?

    How about cases where we want the context to be used with an as clause?

    with ctx_mgr as resource:
    <operations on resource>

    Continue reading...

Compartilhe esta Página