Style question on recursive generators

Carlos Ribeiro carribeiro at gmail.com
Mon Oct 18 15:16:53 EDT 2004


On Mon, 18 Oct 2004 20:54:21 +0200, Alex Martelli <aleaxit at yahoo.com> wrote:
> 
> On 2004 Oct 18, at 16:57, Carlos Ribeiro wrote:
>     ...
> > def walk(self):
> >    """generator-based recursive tree traversal"""
> >    yield child
> >    for child in childs:
> 
> Btw, what are this 'child' and 'childs', _globals_?  I assume you must
> mean something like self and self.children, but as that may become
> important in further discussion it would be nice to be more precise in
> the example.

Sorry. It's pseudo code, but it's _so_ obviously broken :-(  Should
have taken more care...

def walk(self):
  """generator-based recursive tree traversal"""
  yield self
  for child in self.childs:
       transfer child.walk()

> How does the semantics of this differ from those of
>           for x in child.walk(): yield x

I was thinking about something along the lines of a tail recursion
elimination -- sorts of, I mean. Something like "call the child.walk()
code, but yield results direct to the original caller". So you're
right, this is just synctatic sugar, but bad sugar at it :-) (one with
a bitter taste, that is).

But rest assured that I'm now convinced that the original recursive
generator is the way to go, and the my discomfort with it is not
justified. It seemed weird at first, as if I was doing something wrong
-- having to loop over an iterator just to return its members. But
that's just fine.

> If the issue is strictly one of whether it's worth somehow making
>      for x in y: yield x
> terser (by a new kw, combination of kw, and/or punctuation) I guess we
> can discuss that (I just don't see the gain to offset the price of
> introducing new syntax and one more language thing to learn for
> Pythonistas and newcomers to Python).  If you mean something different
> for your 'transfer' then maybe you could clarify _what_...

In the future, and _if_ this idiom (recursive generators) becomes
common enough, maybe it's justified to talk about a new idiom, method
or keyword to support/facilitate it. Not now, really.


-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list