PEP 255: Simple Generators

Paul Prescod paulp at ActiveState.com
Wed Jun 20 22:53:16 EDT 2001


David Bolen wrote:
> 
>...
> 
> >           If generators absolutely have to reuse syntax (which is not the
> > case), I would prefer the keyword 'class' over 'def', since calling a
> > generator creates an instance.
> 
> But so does any number of factory functions that return objects (form
> closures, etc...), e.g.:
> 
>     def f():
>         return UserList.UserList([1,2,3])
> 
> (using UserList to avoid the type/class question)

(as I've said in the python-iterators mailing list) The interesting
thing isn't what gets returned. The interesting thing is what the
compiler does to make sure that an iterator gets returned. It is
radically different than a regular function. Consider:

>>> def a(foo):
...     print "Testing foo"
...     if foo:
...         print "foo was true"
...     else:
...         print "foo was not true"
...     return 5
...
>>> def b(foo):
...     print "Testing foo"
...     if foo:
...         print "foo was true"
...     else:
...         print "foo was not true"
...     yield 5
...
>>> a(1)
Testing foo
foo was true
5
>>> a(0)
Testing foo
foo was not true
5
>>> b(1)
<generator object at 007B6710>
>>> # where is my output???
...
>>> b(0)
<generator object at 007E12F8>
>>> # where is my output???
...
>>>

These two functions were compiled in very different ways. The return
value is irrelevant.

-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list