homepage

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 eric.smith, ncoghlan, serhiy.storchaka
Date 2018年07月08日.04:14:21
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1531023262.45.0.56676864532.issue34067@psf.upfronthosting.co.za>
In-reply-to
Content
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)
History
Date User Action Args
2018年07月08日 04:14:22ncoghlansetrecipients: + ncoghlan, eric.smith, serhiy.storchaka
2018年07月08日 04:14:22ncoghlansetmessageid: <1531023262.45.0.56676864532.issue34067@psf.upfronthosting.co.za>
2018年07月08日 04:14:22ncoghlanlinkissue34067 messages
2018年07月08日 04:14:21ncoghlancreate

AltStyle によって変換されたページ (->オリジナル) /