[Python-ideas] Make "yield" inside a with statement a SyntaxError

Elazar elazarg at gmail.com
Wed Aug 8 02:31:35 EDT 2018


On Tue, Aug 7, 2018 at 11:16 PM Ken Hilton <kenlhilton at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180807/bf891f71/attachment.html>


More information about the Python-ideas mailing list