Recursive Generator Error?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Oct 21 22:36:14 EDT 2012


On Sun, 21 Oct 2012 17:40:41 -0700, David wrote:

> If I have one "yield" in function, the function will become generator,

Almost correct. The function becomes a *generator function*, that is, a 
function that returns a generator object.

Sometimes people abbreviate that to "generator", but that is ambiguous -- 
the term "generator" can mean either the function which includes yield in 
it, or the object that is returned.

> and it can only be called in the form like "for item in function()" or
> "function.next()", and call the function directly will raise error, is
> it right?

You can call the function directly, and it will return an generator 
object. You don't have to iterate over that generator object, although 
you normally will.

Example:

py> def test():
...     yield 42
... 
py> test
<function test at 0xb7425764>
py> type(test)
<type 'function'>
py> x = test()
py> x
<generator object test at 0xb71d4874>
py> type(x)
<type 'generator'>


-- 
Steven



More information about the Python-list mailing list