This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients daniel.urban, eric.araujo, giampaolo.rodola, hniksic, michael.foord, ncoghlan, pitrou, r.david.murray, rhettinger, vstinner
Date 2010-10-13.22:49:09
SpamBayes Score 4.7877267e-09
Marked as misclassified No
Message-id <1287010152.4.0.117206534989.issue10049@psf.upfronthosting.co.za>
In-reply-to
Content
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)
History
Date User Action Args
2010-10-13 22:49:12ncoghlansetrecipients: + ncoghlan, rhettinger, pitrou, vstinner, giampaolo.rodola, hniksic, eric.araujo, r.david.murray, michael.foord, daniel.urban
2010-10-13 22:49:12ncoghlansetmessageid: <1287010152.4.0.117206534989.issue10049@psf.upfronthosting.co.za>
2010-10-13 22:49:10ncoghlanlinkissue10049 messages
2010-10-13 22:49:09ncoghlancreate