[Python] Python 2.5 __missing__()

Bob Miller kbob at jogger-egg.com
Fri Oct 27 07:43:09 PDT 2006


Python 2.5 allows classes derived from dict to define a
__missing__(self, key) method.  That means that you can write a
memoized function like this.

    >>> class MemoFibonacci(dict):
    ...     def __missing__(self, n):
    ...         self[n] = 1 if n < 2 else self[n - 1] + self[n - 2]
    ...         return self[n]
    ...     def __call__(self, n):
    ...         return self[n]
    ...
    >>> fib = MemoFibonacci()
    >>> [fib(i) for i in range(7)]
    [1, 1, 2, 3, 5, 8, 13]

Note the gratuitous use of a conditional expression too. (-:

-- 
Bob Miller                              K<bob>
                                        kbob at jogger-egg.com


More information about the Python mailing list