[Tutor] generator object

monikajg at netzero.net monikajg at netzero.net
Wed Aug 31 12:58:42 EDT 2016


Thank you everybody. This was very helpful
Monika

---------- Original Message ----------
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] generator object
Date: Wed, 31 Aug 2016 21:24:57 +1000

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
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

____________________________________________________________
moneynews.com (Sponsored by Content.Ad)
5 Stocks to Buy Now | Massive Market Correction
http://thirdpartyoffers.netzero.net/TGL3241/57c70d06c606fd062da7st02duc


More information about the Tutor mailing list