How to use a python generator

  • 2020-04-02 13:11:19
  • OfStack

What is a generator?

A generator is a function that contains the special keyword yield. When called, the generator function returns a generator. You can use send, throw, and close methods to let the generator interact with the outside world.

Generators are also iterators , but it's not just an iterator, it has the next method and it behaves exactly like an iterator. So generators can also be used in python loops,

How is the generator used?

Let's start with an example:


#!/usr/bin/python
# -*- coding: utf-8 -*-
def flatten(nested):
    for sublist in nested:
        for element in sublist:
            yield element
nested = [[1,2],[3,4],[5,6]]
for num in flatten(nested):
    print num,

So it's 1,2,3,4,5,6

Recursive generator:


#!/usr/bin/python
# -*- coding: utf-8 -*-
def flatten(nested):
    try:
        for sublist in nested:
            for element in flatten(sublist):
                yield  element
    except TypeError:
        yield nested
for num in flatten([[1,2,3],2,4,[5,[6],7]]):
    print num

The result is: 1, 2, 3, 2, 4, 5, 6, 7

Let's take a look at the nature of generators

First look:


#!/usr/bin/python
# -*- coding: utf-8 -*-
def simple_generator():
    yield 1
print simple_generator
def repeater(value):
    while True:
        new  = (yield value)
        if new is not None: value = new

r = repeater(42)
print r.next()
print r.send('hello,world!')

The result is:


<function simple_generator at 0x10c76f6e0>
42
hello,world!

It can be seen that:
1) a generator is a function
2) the generator has a next method
3) the generator can use the send method to interact with the outside world.


Related articles: