Bug in python!? persistent value of an optional parameter in function!

Paul Rubin http
Wed Mar 7 23:28:45 EST 2007


Steven D'Aprano <steve at REMOVEME.cybersource.com.au> writes:
> def factorial(n, _cache={}):
>     try:
>        return _cache[n]
>     except KeyError:
> There are other ways of implementing caches, but this is quick and easy
> and works well for many functions.

I like this better (examples are untested):

    def factorial(n):
       try:
          return factorial.cache[n]
       except KeyError: pass
       ...
    factorial.cache = {}

you could even use a decorator:

    def memoize(f):  # memoize a 1-arg function
       f.cache = {}
       def g(f,x):
          if x in f.cache: return f.cache[x]
          return f.cache.setdefault(x, f(x))
       return functools.partial(g,f)
    ...

    @memoize
    def factorial(n):
       return 1 if n==0 else n*factorial(n-1)



More information about the Python-list mailing list