On Tue, Aug 7, 2018 at 11:16 PM Ken Hilton <kenlhil...@gmail.com> wrote:

> ...
> Now, let's take a look at the following scenario:
>
>     def read_multiple(*filenames):
>         for filename in filenames:
>             with open(filename) as f:
>                 yield f.read()
>
> Can you spot the problem? The "with open(filename)" statement is supposed
> to ensure that the file object is disposed of properly. However, the "yield
> f.read()" statement suspends execution within the with block, so if this
> happened:
>
>     for contents in read_multiple('chunk1', 'chunk2', 'chunk3'):
>         if contents == 'hello':
>             break
>
> and the contents of "chunk2" were "hello" then the loop would exit, and
> "chunk2" would never be closed! Yielding inside a with block, therefore,
> doesn't make sense and can only lead to obscure bugs.
>

Instead of disallowing code, this is a case for allowing with expressions:

    def read_multiple(*filenames):
        for filename in filenames:
            yield (f.read() with open(filename) as f)

Elazar
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to