AOP use cases

Terry Reedy tjreedy at udel.edu
Thu Apr 22 23:52:08 EDT 2004


"Anton Vredegoor" <anton at vredegoor.doge.nl> wrote in message
news:40888443$0$126$3a628fcd at reader3.nntp.hccnet.nl...
> "Terry Reedy" <tjreedy at udel.edu> wrote:
>
> >Hmmm.  When I started this reply, I was going to emphasize that
'separating
> >concerns' is much less efficient than more directly writing
>
> The problem is *which* concerns are to be separated.
>
> def fgen():
>     #generate fibonacci sequence
>     a,b = 0,1
       # add yield a to define fib(0) as 0, as some do
>     while 1:
>         a,b = b,a+b
>         yield a

> def fib(n, L = [], g = fgen()):
>     #interface with fibonacci generator
>     if n < 0 :
>         return 1
>     while len(L) <= n:
>         L.append(g.next())
>     return L[n]

Nice.  Generalizing the wrapper gives

def listify(gen):
    it = gen()
    cache = []
    def func(n):
        while len(cache) <= n:
            cache.append(it.next())
        return cache[n]
    return func

fib = listify(fgen)

Alternative is
def listify(iterable):
   it = iter(iterable)
...
#which then requires
fib = listify(fgen())

I agree that separating and wrapping the function as generator or iterator
is even better that as regular function.  I have use for this.  Thanks.

Terry J. Reedy







More information about the Python-list mailing list