To understand how
yield works, you need to understand iterables, iterators, and generators
An iterable is an object capable of returning its members one at a time. Iterables include:
All sequence types, such as:
Some none-sequence types, such as:
- file objects
- any objects of user-defined classes with an
__iter__() method or with a
__getitem__() method that implements Sequence
semantics (see below)
Iterables can be used in a
for loop and in many other places where a sequence is needed:
When an iterable object is passed to the built-in function
iter(), it returns an iterator for the object.
The iterator is good for one pass over the set of values
It is usually not necessary to call
iter() directly, as the
for statement does this for you, creating a temporary unnamed
variable to hold the iterator for the duration of the loop.
User-defined iterables need to define one of
Called when an iterator is required for a container.
Iterator objects also need to implement this method; they are required to return themselves.
Called to implement
For sequence types, the accepted keys should be integers or slice objects.
The interpretation of negative slices is the responsibility of the
If key is of the wrong type, a
TypeError may be raised.
If the key is of a value outside the set of indexes for the sequence, an
IndexError should be raised.
For mapping types, if key is missing, a
KeyError should be raised.
An iterator is an object representing a stream of data.
Calls to the object’s
__next__() method (or passing it to the built-in function
next()) return successive items in the
When no more data are available, a
StopIteration exception is raised.
The iterator is then exhausted, and any subsequent calls to
__next__() method will raise a
Iterators are required to have an
__iter__() method so every iterator is also iterable and may be used in most places where
other iterables are accepted.
The word generator refers to two things: a generator function and a generator iterator.
A generator function is like a normal function except that it contains one or more
When a generator function is called, its code is not executed, and instead it returns a generator iterator.
This is an iterator that controls the execution of the generator function in response to calls to the
Each yield in the associated generator function causes execution to be temporarily suspended. When the iterator resumes, execution continues from where it left off.