Message118599
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) |
|
Date |
User |
Action |
Args |
2010-10-13 22:49:12 | ncoghlan | set | recipients:
+ ncoghlan, rhettinger, pitrou, vstinner, giampaolo.rodola, hniksic, eric.araujo, r.david.murray, michael.foord, daniel.urban |
2010-10-13 22:49:12 | ncoghlan | set | messageid: <1287010152.4.0.117206534989.issue10049@psf.upfronthosting.co.za> |
2010-10-13 22:49:10 | ncoghlan | link | issue10049 messages |
2010-10-13 22:49:09 | ncoghlan | create | |
|