The yield keyword

Generators are defined by any Python function which uses the yield keyword at least once in its definition. They may also contain the return keyword with no arguments, and just like any other function, there is an implicit return at the end of the definition.

To understand what generators do, let's start with a simple example at the Python REPL. Let's define the generator, and then we'll examine how the generator works.

Generator functions are introduced by def, just as for a regular Python function:

>>> def gen123():
... yield 1
... yield 2
... yield 3
...

Now let's call gen123() and assign its return value to g:

>>> g = gen123()

As you can see, gen123() is called just like any other Python function. But what has it returned?

>>> g
<generator object gen123 at 0x1006eb230>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset