PEP 255: Simple Generators
Paul Svensson
paul at svensson.org
Sat Jun 23 08:44:32 EDT 2001
"Andrew Dalke" <dalke at acm.org> writes:
>Carsten Geckeler:
>>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.
>
>There isn't quite enough information to distinguish between at
>least some class definitions and function definitions without the
>use of a keyword. Consider
>
>>>> class SuperTest:.
>... pass.
>...
>>>> def Test(SuperTest):.
>... def __init__(self, spam):.
>... self.spam = spam.
>... def __str__(self):.
>... return str(self.spam)
>>>> t = Test("eggs")
>>>> str(t)
>'None'
>>>>
>
>Changing the 'def Test' to 'class Test' changes the
>entire meaning of the code.
Of course -- as would changing to 'gen Test'.
Consider an alternate universe,
where "def" is used to define all of classes, functions, and generators.
It's easy to tell one from the other:
Generators use "yield",
functions use "return",
classes use neither.
Obviously,
someone decided that in the case of def/class,
this was not a good idea.
How is def/gen different ?
Try writing a generator that always yields a fixed result;
in some cases an empty list.
Which of these would you like to explain to a newbie ?
---------------------------------------
def one(): gen two():
yield 1 yield 1
yield 2
---------------------------------------
def empty(): gen empty():
if 0: pass
yield
---------------------------------------
def empty(): def empty():
return iter(()) return ()
---------------------------------------
/Paul
More information about the Python-list
mailing list