Nick Coghlan <ncogh...@gmail.com> added the comment:

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)

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue34067>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to