PEP 255: Simple Generators

Carsten Geckeler uioziaremwpl at spammotel.com
Fri Jun 22 11:34:35 EDT 2001


On 20 Jun 2001, David Bolen wrote:
> "Rainer Deyke" <root at rainerdeyke.com> writes:
[snip]
> > 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)
>
> So do we need different syntax for all types of functions that might
> return instances of some object?  Eventually this could devolve into
> the point elsewhere in the thread of wanting defint rather than def
> for functions returning an integer.

This argument makes no sense.  Let us look at class definitions and how to
create an instance:

class Test:
    def __init__(self):
...

test = Test()

So Test is called like a function and returns an instance.  But why make a
different syntax ("class") for defining it?  Just because it returns an
instance instead an integer or another object?  According to your
argument, "def" would be fine.  We would just have to insert a magic class
statement somewhere, flagging the definition as a class definition (just
as yield flags a generator definition).

Another problem:  Generator definitions are nothing like function
definitions.  With the same argument (also raised by Tim), that it looks
like a function from the caller's POV (like a class), is not sufficient to
define it with "def".  Because it does not have a "return" statement,
which returns the iterator.  And that's the difference to any regular
function, also to any factory function, because they include an explicit
"return" statement.

Cheers, Carsten
-- 
Carsten Geckeler






More information about the Python-list mailing list