On 20/03/2006, at 17:44, Ido Abramovich wrote:

I want to build a generator that can update it's content during runtime, but I'm not sure whether what I'm doing works by mistake or works by purpose.

I've read PEP-255 about Generators, but nothing is mentioned about changing the inner space of the generator during runtime - this could mean that "it works by mistake" but from what I understand about generators - this behavior is a by-product of the algorithm.

A generator does not have any "space", it simply yield an item on each iteration. Nobody cares how the items are generated.


I'm attaching an example of a generator and an iterator

The second example, main2() - is just a for loop

that are supposed to do produce the same output. The Iterator doesn't work and produces a RuntimeError while the Generator finishes the task successfully.

Which does not allow changing the collection.

    for i in collection:
        # add item to collection <-- you can't change it in for loop

If you try to use for loop in the generator, it will also break when you add items to the collection:

    def generator():
        for i in collection:
            # add item to collection <-- will break here
            yield i

main2 will work using while and pop:

    while collection:
        i = collection.pop()
        # add item to collection



What do you think? is it safe to use the generator function? if not - do you have another safe approach to add items to a generator during runtime?

The generator is better if you like to hide the generation of new items from the caller, and bad if the caller want to control the generation.


Best Regards,

Nir Soffer

לענות