[Python-ideas] Generators are iterators

Andrew Barnert abarnert at yahoo.com
Thu Dec 11 00:58:54 CET 2014


On Dec 10, 2014, at 14:22, Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, Dec 11, 2014 at 9:11 AM, Alexander Belopolsky
> <alexander.belopolsky at gmail.com> wrote:
>> I think the problem is with the term "generator function" because what we
>> call "generator function" is neither a generator nor a function.  It is a
>> callable that returns a generator.   To our excuse, this abuse of language
>> is not uncommon.  People often say "integer function" when they mean a
>> function with integer domain and range (or even just range).
> 
> Interesting. Are you saying the 'def' statement may produce a thing
> that isn't a function, even though it calls itself a function?
> 
>>>> def gen():
> ...     yield 1
> ...
>>>> type(gen)
> <class 'function'>
>>>> type(gen())
> <class 'generator'>
> 
> It's a function that returns an iterator, same as this is:
> 
>>>> def nongen():
> ...     return iter((1,2,3))
> ...
>>>> type(nongen)
> <class 'function'>
>>>> type(nongen())
> <class 'tuple_iterator'>
> 
> A generator function is a function that returns a generator object. Is
> this problematic?

def whatisthis():
    return gen()

That's not a generator function, but it is a function that returns a generator.

(That's a bit of a silly case, but there's plenty of real-life code like this. In fact, IIRC, a couple of the functions in itertools are generator functions in the pure Python implementation but regular functions that return iterators in the C implementation.)


> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list