[Python-ideas] Make "yield" inside a with statement a SyntaxError
Barry Scott
barry at barrys-emacs.org
Wed Aug 8 03:05:53 EDT 2018
On Wednesday, 8 August 2018 07:14:47 BST Ken Hilton 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()
In this particular case you can fix the code:
def read_multiple(*filenames):
for filename in filenames:
with open(filename) as f:
result = f.read()
yield result
Of course if you used readline() and not read() the problem returns.
But so long as you do not leak the generator the file will be closed
immediately after the loop as the ref count of the generater hits 0.
Barry
More information about the Python-ideas
mailing list