31.07.18 00:26, Oscar Benjamin пише:
On 30 July 2018 at 20:15, Rudy Matela <rudy@matela.com.br> wrote: Yielding from a with block should be discouraged rather than given special syntax. There is essentially a contradiction between the meaning/purpose of yield (suspend indefinitely) and with (definitely call __exit__).
If I partially iterate over g as in
for line in g: break
then at this point g is suspended and f.__exit__ has not been called, so the file is not closed. I may choose to iterate over g later or not, so it has to remain in suspension just in case. In practice if you do this in CPython then f.__exit__ will *probably* be invoked indirectly by g.__del__ if/when the gc collects g. This defeats the main point of using with-open though which is to avoid depending on the gc for closing files.
Concur with Oscar.