Skip to content
Advertisement

Misunderstood python yield

This code below works correct :

JavaScript

But this function raises StopIteration. I don’t understand why ?

JavaScript

Advertisement

Answer

You have:

JavaScript

Notice line = f.readline() This only reads 1 line from the file.

Compare:

JavaScript

with this:

JavaScript

yield can only be called once with a particular object or expression. Once it is used by the receiver it must be regenerated. So you need a loop around reading each line of the file.

You can use your second (less readable) form this way:

JavaScript

You need a loop to create the the items to yield. In your first case, for line in f: yield line is a loop.

I would rewrite your function this way:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement