▲ | unsnap_biceps 5 days ago | |
I'm fairly unfamiliar with python and I don't quite understand what this is actually doing. Does it change anything in the execution or is it just to mark it in a way for IDEs to do something with? | ||
▲ | kstrauser 5 days ago | parent [-] | |
Yes. If a function contains the yield statement, calling that function returns a generator instead of executing its body. For example, here's defining and calling a regular function:
And here's defining and calling a generator:
Notice that the generator's body isn't evaluated until you consume the generator. StopIteration isn't actually an error in usual cases. It just says that the generator doesn't have any more values to return and has exited. For example, that's how Python's for-loop works:
Here it executes the generator's body (including the print() call) until it gets to the return statement. Because it's a generator, it returns as normal and then raises a StopIteration exception, which tells the loop to stop looping. |