Nick Coghlan <ncogh...@gmail.com> added the comment:

To me, this is more a matter of conceptual completeness than one of practical 
utility (ala fractions.Fraction). That said, I *have* personally encountered 
the "I only sometimes want to wrap this code in a CM" situation, so it isn't 
completely impractical, either. Those two factors are enough to reach my 
threshold for it being worthwhile to declare "one obvious way to do it" through 
the contextlib module.

There is a possible alternative approach that may be more intuitive to use and 
read than nullcontext() though:

@contextmanager
def optional_cm(cm, *, use_cm=True): # See naming note below
    if cm is None or not use_cm:
        yield
    else:
        with cm:
            yield

The OP's original example would then look like:

with optional_cm(transaction):
    ...

I suspect readers would find it far easier to remember what optional_cm does 
than to learn to recognise the "or nullcontext()" idiom. It also plays better 
with nested context managers:

with optional_cm(sync_lock), optional_cm(db_transaction), \
     open(fname) as f:
    ...


Naming Note: I nearly suggested "optional_context" as a name for this, but 
realised that would be subtly misleading (suggesting PEP 377 style 
functionality that potentially skipped the statement body, rather than the 
intended semantics of skipping use of the CM)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue10049>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to