How to identify generator/iterator objects?

Kenneth McDonald kenneth.m.mcdonald at sbcglobal.net
Thu Oct 26 01:04:09 EDT 2006


Thanks for all the feedback. Yes the original post was incorrect, it was 
an intellectual burp that had me asking about a instead of f(something).

Boy, that answer's something I would never have known...

Thanks,
Ken

Leo Kislov wrote:
> Michael Spencer wrote:
>   
>> 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.
>>>
>>> Is there a way to do this? Or perhaps another (better) way to achieve
>>> this flattening effect? itertools doesn't seem to have anything that
>>> will do it.
>>>
>>> Thanks,
>>> Ken
>>>       
>> I *think* the only way to tell if a function is a generator without calling it
>> is to inspect the compilation flags of its code object:
>>
>>   >>> from compiler.consts import CO_GENERATOR
>>   >>> def is_generator(f):
>>   ...     return f.func_code.co_flags & CO_GENERATOR != 0
>>   ...
>>   >>> def f1(): yield 1
>>   ...
>>   >>> def f2(): return 1
>>   ...
>>   >>> is_generator(f1)
>>   True
>>   >>> is_generator(f2)
>>   False
>>   >>>
>>     
>
> It should be noted that this checking is completely irrelevant for the
> purpose of writing flatten generator. Given
>
> def inc(n):
>     yield n+1
>
> the following conditions should be true:
>
> list(flatten([inc,inc])) == [inc,inc]
> list(flatten([inc(3),inc(4)]) == [4,5]
>
>   -- Leo
>
>   




More information about the Python-list mailing list