Skip to content Skip to sidebar Skip to footer

Python Create An Iterator/generator With Feedback

Is it possible to create a iterator/generator which will decide on the next value based on some result on the previous iteration? i.e. y = None for x in some_iterator(ll, y): y =

Solution 1:

Did you that you can send to a generator using generator.send? So yes, you can have a generator to change its behaviour based on feedback from the outside world. From the doc:

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator [...]

Example

Here is a counter that will increment only if told to do so.

defconditionalCounter(start=0):
    whileTrue:
        should_increment = yield start
        if should_increment:
            start += 1

Usage

Since iteration with a for-loop does not allow to use generator.send, you have to use a while-loop.

import random

defsome_calculation_on(value):
    return random.choice([True, False])

g = conditionalCounter()

last_value = next(g)

while last_value < 5:
    last_value = g.send(some_calculation_on(last_value))
    print(last_value)

Output

0
0
1
2
3
3
4
4
5

Make it work in a for-loop

You can make the above work in a for-loop by crafting a YieldReceive class.

classYieldReceive:
    stop_iteration = object()

    def__init__(self, gen):
        self.gen = gen
        self.next = next(gen, self.stop_iteration)

    def__iter__(self):
        return self

    def__next__(self):
        if self.nextis self.stop_iteration:
            raise StopIteration
        else:
            return self.nextdefsend(self, value):
        try:
            self.next = self.gen.send(value)
        except StopIteration:
            self.next = self.stop_iteration

Usage

it = YieldReceive(...)
for x in it:
    # Do stuff
    it.send(some_result)

Solution 2:

It's possible but confusing. If you want to keep the sequence of x values and the calculations on x separate, you should do this explicitly by not involving x with an iterator.

defnext_value(x):
    """Custom iterator"""# Bunch of code defining a new xyield new_x


x = NonewhileTrue:
    x = next_value(x)
    x = some_calculation_on(x)
    # Break when you're doneif finished and done:
        break

If you want the loop to execute exactly i times, then use a for loop:

for step in range(i):
    x =next_value(x)
    x = some_calculation_on(x)
    # No break

Solution 3:

defconditional_iterator(y):
    # stuff to create new valuesyield x if (expression involving y) else another_x

for x in conditional_iterator(y):
    y = some_computation(x)

Post a Comment for "Python Create An Iterator/generator With Feedback"