Message321254
That's certainly similar to the problems with contextlib.nested, but I don't think it's as inherently flawed as nested was. What I'd suggest we change the existing example to is this:
from functools import partial
from os import fspath
def process_file(file_or_path):
try:
as_fspath = os.fspath(file_or_path)
except TypeError:
# If it's a file, caller is responsible for closing it
make_cm = partial(nullcontext, file_or_path)
else:
# If it's a path, open file when the context is entered
make_cm = partial(open, as_fspath)
with make_cm() as file:
# Perform processing on the file
Optionally, we could also present a cleaner example where a pre-created context manager is passed in and we're just coping with the fact it may be None:
def update_resource(resource, updates, resource_lock=None):
if resource_lock is None:
resource_lock = nullcontext()
with resource_lock:
resource.apply_updates(updates)
(I'll also note that ExitStack is *far* from being immune to the Ctrl-C problem, as it's implemented in Python itself, which allows its __exit__ method to be interrupted, as well as for interrupt to occur between a resource being created or acquired, and it being registered with the stack) |
|
Date |
User |
Action |
Args |
2018-07-08 04:14:22 | ncoghlan | set | recipients:
+ ncoghlan, eric.smith, serhiy.storchaka |
2018-07-08 04:14:22 | ncoghlan | set | messageid: <1531023262.45.0.56676864532.issue34067@psf.upfronthosting.co.za> |
2018-07-08 04:14:22 | ncoghlan | link | issue34067 messages |
2018-07-08 04:14:21 | ncoghlan | create | |
|