Memoization and encapsulation
bonono at gmail.com
bonono at gmail.com
Sat Dec 31 00:08:09 EST 2005
Steven D'Aprano wrote:
> I was playing around with simple memoization and came up with something
> like this:
>
> _cache = {}
> def func(x):
> global _cache
> if _cache.has_key(x):
> return _cache[x]
> else:
> result = x+1 # or a time consuming calculation...
> _cache[x] = result
> return result
>
> when it hit me if I could somehow bind the cache to the function, I could
> get rid of that pesky global variable.
>
what would be the problem of the following, other than exposing the
cache which the caller may override ?
def func(x,_cache={}):
More information about the Python-list
mailing list