[Python-ideas] Sending to a generator being looped over in a for-loop

Arnaud Delobelle arnodel at googlemail.com
Sat Feb 21 00:55:50 CET 2009


When giving some examples in a previous post, I gave this
tree-traversing example:

class Tree(object):
    def __init__(self, label, children=()):
        self.label = label
        self.children = children
    def __iter__(self):
        skip = yield self.label
        if skip == 'SKIP':
            yield 'SKIPPED'
        else:
            yield 'ENTER'
            for child in self.children:
                yield from child
            yield 'LEAVE'

Here is a tree:

tree = Tree('A', [Tree('B'), Tree('C')])

Here is an example of how to traverse it, avoiding the children of
nodes called 'B'.  I can't use a for-loop as I need to send the
skip-value to the tree iterator and this makes the loop look quite
complicated.  Here's one way to do it:

i = iter(tree)
skip = None
try:
    while True:
        a = i.send(skip)
        print a
	skip = 'SKIP' if a == 'B' else None
except StopIteration:
    pass

Now imagine that the 'continue' statement within a for-loop has an
optional argument that is sent to the generator being looped over at
the next iteration step.  I would then be able to write the loop above
much more simply:

for a in tree:
    print a
    if a == 'B':
        continue 'SKIP'

-- 
Arnaud



More information about the Python-ideas mailing list