Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a __next__() method, the current yield expression always evaluates to None. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to __next__()’s caller. If the generator exits without yielding another value, a StopIteration exception is raised.
This method is normally called implicitly, e.g. by a for loop, or by the built-in next() function.
Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.
Here is a simple example that demonstrates the behavior of generators and generator functions:
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... while True:
... value = (yield value)
... except Exception as e:
... value = e
... print("Don't forget to clean up when 'close()' is called.")
>>> generator = echo(1)
Execution starts when 'next()' is called for the first time.
>>> generator.throw(TypeError, "spam")
Don't forget to clean up when 'close()' is called.