Mutable object as default value and memoization

Using mutable object as default value in Python is ususally considered a bad idea because it may seems to be strange for new comers. There's alot posts on the web that explained the reason why you shouldn't do that, e.g. this one.

But using a mutable object, for example a dict, can be convinient if you want to implement memoization in your function.

Here's an example of memoization to implement factorial:

def factorial_non_memoization(n):
    if n == 0:
        return 1
    else:
        return factorial_non_memoization(n-1)*n

_cache = dict()
def factorial_memoization(n):
    if n == 0:
        _cache[0] = 1
    else:
        _cache[n] = factorial_memoization(n-1)*n
    return _cache[n]

If you need repeatly call to factorial function, the memoized version can save a lot of time. But this function needs an extra global variable, something that smells bad. The fix is simple, write a decorator, and this decorator can even be generalized to memoize any function call.

How about a simple solution, using a mutable object as default value? Here it is:

def factorial(n, _cache={0:1}):
    if n not in _cache:
        _cache[n] = factorial(n-1)*n

    return _cache[n]

Comments !

blogroll

social