New submission from Serhiy Storchaka <storchaka+cpyt...@gmail.com>:

There is a flaw in the example in the documentation for contextlib.nullcontext.

      def process_file(file_or_path):
          if isinstance(file_or_path, str):
              # If string, open file
              cm = open(file_or_path)
          else:
              # Caller is responsible for closing file
              cm = nullcontext(file_or_path)

          with cm as file:
              # Perform processing on the file

The execution can be interrupted by Ctrl-C between opening a file and entering 
a 'with' block. There is the same problem with the simple "with open(path) as 
file:", but it can be easily solved (see issue34066). It is harder to do for 
this example, because there are more opcodes between calling open() and 
entering 'with'. I afraid that this problem can't be solved in general case. 
Maybe contextlib.nullcontext has a flaw similar to the flaw in 
contextlib.nested().

----------
messages: 321226
nosy: ncoghlan, serhiy.storchaka
priority: normal
severity: normal
status: open
title: Problem with contextlib.nullcontext
type: resource usage
versions: Python 3.7, Python 3.8

_______________________________________
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