Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a generator in Python?

Is there a common interface in Python that I could derive from to modify behavior of a generator?

For example, I want to modify an existing generator to insert some values in the stream and remove some other values.

How do I do that?

Thanks, Boda Cydo

like image 408
bodacydo Avatar asked Mar 10 '10 23:03

bodacydo


People also ask

How do you access the generator object in Python?

You need to call next() or loop through the generator object to access the values produced by the generator expression. When there isn't the next value in the generator object, a StopIteration exception is thrown. A for loop can be used to iterate the generator object.

Can you unpack a generator Python?

You can carry out the unpacking procedure for all kinds of iterables like lists, tuples, strings, iterators and generators.

What can you do with a Python generator?

Python Generator functions allow you to declare a function that behaves likes an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object.

How do you make a generator in Python?

Create Generators in Python It is fairly simple to create a generator in Python. It is as easy as defining a normal function, but with a yield statement instead of a return statement. If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function.


2 Answers

You can use the functions provided by itertools to take a generator and produce a new generator.

For example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.

Take a look at the documentation for other examples, including things like ifilter, dropwhile and islice to name just a few more.

like image 154
Mark Byers Avatar answered Oct 05 '22 11:10

Mark Byers


You can just wrap the generator in your own generator.

from itertools import count

def odd_count():
    for i in count():
        if i % 2:
            yield i
like image 44
Chris B. Avatar answered Oct 05 '22 12:10

Chris B.