Message118193
The difference here is the one pointed out in the original post: for a function, you usually only care about having a value, so if you don't want to call it, you can just swap in a None value instead. If you need an actual callable, then "lambda:None" fits the bill.
The with statement isn't quite so forgiving. You need a genuine context manager in order to preserve the correct structure in the calling code. It isn't intuitively obvious how to do that easily. While not every 3-line function needs to be in the standard library, sometimes they're worth including to aid discoverability as much as anything else.
However, I don't see the point in making it a singleton and the name should include the word "context" so it doesn't becoming ambiguous when referenced without the module name (there's a reason we went with contextlib.contextmanager over contextlib.manager).
Something like:
class nullcontext():
"""No-op context manager, executes block without doing any additional processing.
Used as a standin if a particular block of code is only sometimes
used with a normal context manager:
with optional_cm or nullcontext():
# Perform operation, using the specified CM if one is given
"""
def __enter__():
pass
def __exit__(*exc_info):
pass |
|
Date |
User |
Action |
Args |
2010-10-08 12:03:22 | ncoghlan | set | recipients:
+ ncoghlan, pitrou, vstinner, hniksic, eric.araujo, michael.foord |
2010-10-08 12:03:22 | ncoghlan | set | messageid: <1286539402.71.0.997850073548.issue10049@psf.upfronthosting.co.za> |
2010-10-08 12:03:20 | ncoghlan | link | issue10049 messages |
2010-10-08 12:03:18 | ncoghlan | create | |
|