[Tutor] generator object

Steven D'Aprano steve at pearwood.info
Wed Aug 31 07:24:57 EDT 2016


On Wed, Aug 31, 2016 at 04:12:24AM +0000, monikajg at netzero.net wrote:
> 
> So generator function returns generator object according to Aaron 
> Maxwell. But does this mean that each time yields "returns" it is a 
> generator object? So if there are 5 yield "returns" there are 5 
> generator objects? Or is there always only one generator object 
> returned by the generator functions? 
> Can somebody please explain?


The terminology can be confusing, because there are multiple very 
similar terms which are related. But fortunately, we can ask Python 
itself for help!

Let's start by using the inspect module to take a look at an ordinary 
function:

py> import inspect
py> def func():
...     return 19
...
py> inspect.isfunction(func)
True
py> inspect.isgenerator(func)
False
py> inspect.isgeneratorfunction(func)
False


So that's pretty straight-forward: a regular function is just a 
function.

What happens if we make something which people often call "a generator"? 
Let's make a function and use yield instead of return:

py> def gen():
...     yield 19
...
py> inspect.isfunction(gen)
True
py> inspect.isgenerator(gen)
False
py> inspect.isgeneratorfunction(gen)
True

So there you have it: a function with "yield" inside is still a 
function, but it is also a "generator function". Even though people 
often call it "a generator", it isn't technically a generator. It's a 
generator function.


If we call the generator function, what do we get?

py> it = gen()
py> inspect.isfunction(it)
False
py> inspect.isgenerator(it)
True
py> inspect.isgeneratorfunction(it)
False


So there we have it, all official: calling a generator FUNCTION returns 
a generator.

But in practice, people will use the term "generator" for both generator 
functions like "gen", and the actual generators like "it". Normally the 
distinction isn't important, or it is obvious. When it isn't obvious, 
you can avoid ambiguity by referring to "gen" as the generator function, 
and "it" as the generator object.



-- 
Steve


More information about the Tutor mailing list