Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31867

Re: Recursive Generator Error?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Recursive Generator Error?
Date 2012-10-21 19:59 -0400
References <d1dbc8a7-1ec6-474c-96d7-b95a066125dd@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2608.1350863992.27098.python-list@python.org> (permalink)

Show all headers | View raw


On 10/21/2012 7:29 PM, David wrote:
> I have a tree-like data structure, the basic elements are hash tables,
> and they are grouped into lists, like [[{'a':1},[{'b':2}]]].
> And I want to flat the lists and visit hash table one by one, like {'a':1}, {'b':2}.
> But my program didn't work as I wish. When it entered the 2nd
> flat_yield, it threw a GeneratorExit. Is there anything wrong?

1. The Python version is not specified.
2. You used 2.x; in 3.3 the code does exactly what I would expect, which 
is to say, nothing. No output, no error, no traceback ;-)
3. The traceback is missing from this post.

> #- - - - - - - - - -
> def flat_yield(tbl_list):
>      for t in tbl_list:
>          if type(t) == type({}):
>              yield t
>          elif type(t) == type([]):
>              flat_yield(t)

4. Think harder about what that expression does.

> a = [[{'a':1},[{'b':2}]]]
> for i in flat_yield(a):
>      print i

Hint: it calls flat_yield, which returns a generator, which is then 
discarded. You might have well written 'pass'.

Solution: use the recursively called generator and recursively yield 
what it yields. Replace 'flat_yield(t)' with

             for item in flat_yield(t):
                 yield item

and the output is what you want.

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Recursive Generator Error? David <zhushenli@gmail.com> - 2012-10-21 16:29 -0700
  Re: Recursive Generator Error? Terry Reedy <tjreedy@udel.edu> - 2012-10-21 19:59 -0400
    Re: Recursive Generator Error? David <zhushenli@gmail.com> - 2012-10-21 17:40 -0700
    Re: Recursive Generator Error? David <zhushenli@gmail.com> - 2012-10-21 17:40 -0700
      Re: Recursive Generator Error? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-22 02:36 +0000

csiph-web