How to identify generator/iterator objects?
Leo.Kislov at gmail.com
Wed Oct 25 23:18:44 CEST 2006
Kenneth McDonald wrote:
> I'm trying to write a 'flatten' generator which, when give a
> generator/iterator that can yield iterators, generators, and other data
> types, will 'flatten' everything so that it in turns yields stuff by
> simply yielding the instances of other types, and recursively yields the
> stuff yielded by the gen/iter objects.
> To do this, I need to determine (as fair as I can see), what are
> generator and iterator objects. Unfortunately:
> >>> iter("abc")
> <iterator object at 0x61d90>
> >>> def f(x):
> ... for s in x: yield s
> >>> f
> <function f at 0x58230>
> >>> f.__class__
> <type 'function'>
> So while I can identify iterators, I can't identify generators by class.
But f is not a generator, it's a function returning generator:
>>> def f():
... print "Hello"
... yield 1
Traceback (most recent call last):
File "<input>", line 1, in ?
TypeError: iteration over non-sequence
<generator object at 0x016C7238>
Notice, there is no side effect of calling f function.
More information about the Python-list