def foo(n): for i, num in enumerate(range(n)): yield i, num raise StopIteration def foo(n): for i, num in enumerate(range(n)): yield i, num return According to PEP479, the raise of StopIteration to end the loop of a generator may lead to hard to find bugs. This PEP specify that raise StopIteration has to be replaced by a simple return statement.