PEP 255: Simple Generators

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Tue Jun 19 15:42:46 EDT 2001


Mon, 18 Jun 2001 11:32:31 -0700, Russell E. Owen <owen at astrono.junkwashington.emu> pisze:

> * A generator looks like a function until you find the "yield" statement 
> inside. I think this will make the code much harder to read. One keyword 
> buried anywhere in a function totally changes its behavior.

I agree that it's strange, but I prefer the PEP's syntax to any of
the alternatives that were proposed. Because each proposal introduced
a new pseudo-keyword or new syntax instead of reusing existing syntax
in some intuitive way.

An intuitive syntax could for example mirror the usage syntax in the
definition syntax, such that it could be treated as an equation in some
analogical way to a normal definition. Unfortunately I found absolutely
no way to sensibly put 'for' in a generator definition header.

An example of such intuitive syntax is this:
    def self.f(arg): pass
The only problem is that they are two equally intuitive interpretations :-)
It can mean either
    def f(self, arg): pass
    # In a class where o.f(a) will be transformed back into f(o, a)
or
    self.f = lambda arg: None
i.e. it's not clear whether "self" is *used* or *defined* here. Oops.

Another example of such intuitive syntax is declaration of C pointers
and arrays... Well, I think it's horrible compared to alternatives
(e.g. Pascal), so perhaps my rule about advantages of a definition
header mirroring the usage is not that generally applicable...

It does apply to function and value definitions in most functional
languages however - finally a case where it works:
    f x y = (x+y)*(x-y)
    -- Implies that 'f 3 4' means '(3+4)*(3-4)'
    (x, y) = (3, 4)
    -- Implies that 'y' means '4'
    z = [0]
    -- This is a special case of either of the above (function with no
    -- arguments or a pattern consisting of a variable), but both ways
    -- give the same result, so it doesn't matter (almost).


> 1) Have users explicitly say "raise StopIter" when they mean it.

I would strongly oppose it for a simple reason: the fact that stopping
is implemented by raising StopIter is not necessarily visible when a
generator is used - because it's usually used by a 'for' loop - so it
should not be obligatorily visible when a generator is defined. I.e.
one can happily define and use generators without mentioning StopIter
at all.

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list