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

Mathias Panzenböck grosser.meister.morti at gmx.net
Sat Feb 21 01:03:37 CET 2009


Ok, this is a good example (IMHO). So +1 from me. But I'm not sure about the 
syntax. Maybe "yield for child"?

Arnaud Delobelle wrote:
> 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'
> 




More information about the Python-ideas mailing list