How to change a generator in Python?

Is there a generic interface in Python that I could extract to change the behavior of the generator?

For example, I want to modify an existing generator to insert some values ​​into a stream and delete some other values.

How to do it?

Thanks, Boda Sido

+4
source share
2 answers

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

For example, you can use takewhile until the predicate is executed, and chain in a new series of values.

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

+6
source

You can simply wrap the generator in your own generator.

from itertools import count def odd_count(): for i in count(): if i % 2: yield i 
+3
source

Source: https://habr.com/ru/post/1303740/


All Articles