3

I sometimes end up in a situation where I'm working with a generator whose members are themselves generators (and so on for n levels).

When debugging, printing these results in the useless <generator object blah at blah>

Obviously I can do print(list(my_gen)) to convert the top level to a list. But then I get

[<generator object blah at blah>, <generator object blah at blah>, <generator object blah at blah>]

which is equally useless.

Is there a simple command for printing a nested generator evaluated all the way down?

I know that I could write a recursive function to do this, but I'm looking for a simple method.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
user8493571
  • 119
  • 4
  • 1
    [this](https://stackoverflow.com/questions/11377208/recursive-generator-for-flattening-nested-lists) may be related. note recursively printing the generators will exhaust them (if you don't use `tee` or something) - so printing them will change them. – hiro protagonist Feb 22 '20 at 07:30
  • 2
    "I know that I could write a recursive function to do this, but I'm looking for a simple method." That *is* a simple method. You don't have to use recursion either, but regardless, you have to write something because there is no built-in solution if that's what you are looking for – juanpa.arrivillaga Feb 22 '20 at 07:46
  • 1
    @juanpa.arrivillaga Can we do it without using recursion? Can you please elaborate on how to do it. I thought recursion is the only way to go. – Ch3steR Feb 22 '20 at 08:17

1 Answers1

3

You can write a recursive function to evaluate N-level nested generator. I don't think a built-in function exists for this.

import types

def _gen(gen):
    if not isinstance(gen,types.GeneratorType):
        return gen
    else:
        return [_gen(i) for i in gen]

my_gen=((j for j in range(i)) for i in range(10))

print(_gen(my_gen))

[[],
 [0],
 [0, 1],
 [0, 1, 2],
 [0, 1, 2, 3],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4, 5],
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6, 7],
 [0, 1, 2, 3, 4, 5, 6, 7, 8]]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58