Callable generators (PEP 288: Generator Attributes, again)

Michele Simionato michele.simionato at poste.it
Wed Nov 19 13:28:27 EST 2003


"Francis Avila" <francisgavila at yahoo.com> wrote in message news:<vrmpthqfk8bc8b at corp.supernews.com>...
> I'm suggesting the PEP's functionality, not its syntax and semantics.  My
> contention is that the PEP regards generators as too class-like, when they
> are more naturally considered as function-like.
> 
> For example, your iterator class/instance would look like this:
> 
> def iterator(x=1)(x):
>     yield x
>     yield x
> 
> print iterator.next() # -> 1
> print iterator(5)  # -> 5
> 
> The local name "x" is updated (according to the second parameter list in the
> function definition) right after the yield of the previous call when
> iterator is called, behaving like a state-persistent callable function.  If
> it's just "nexted", it behaves like a plain old iterator.

I see what you mean, now. Still, the notation is confusing, since I
do think an iterator as something which it obtained by "instantiating"
a generator. On the other hand, your iterator(5) would not be a newly
"instantiated" iterator, but the same iterator with a different
parameter x. So, you would need a different syntax, as for instance
iterator[5]. Still, I do think this would be confusing. The class
solution would be more verbose but clearer.
 
> Here's an efficient reversable generator:
> 
> def count (n=0)(step=1):
>     while True:
>         yield n
>         n += step

Yeah, it is lightweight, but a class derived from "Iterator" 
would be only one line longer, so I am not convinced. Also,
people would start thinking that you can define regular
functions with two sets of arguments, and this would generate
a mess ...

                      Michele




More information about the Python-list mailing list