[Python] Python 2.5 __missing__()

Bob Miller kbob at jogger-egg.com
Fri Oct 27 15:21:59 PDT 2006


Rob Hudson wrote:

> Hey, that's cool.  :)
> 
> How do you know what's going to be passed to __missing__()?  Is it 
> always the same as __call__()?

fib is a dict.  Whenever fib[k] is referenced where k is not
in the dict, the __missing__ method is called.

The __call__ method is just there so you can treat it like
a function.  fib(3) is equivalent to fib[3].

In the Fibonacci example, the __missing__ method puts the entry into
the dict.  In another example, it might throw an exception on
Thursdays.

    >>> class Sillier(dict):
    ...     def __missing__(self, key):
    ...         if time.localtime().tm_wday == 3:
    ...             raise NeverCouldGetTheHangOfThursdays()
    ...         self[key] = 'silly'
    ...     return self[key]
    ... 
    >>> s = Sillier()
    >>> s['a'] = 1
    >>> s['a']
    1
    >>> s['b']           # on Friday
    'silly'
    >>> s['b']           # on Thursday
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in __missing__
    __main__.NeverCouldGetTheHangOfThursdays

> Bob Miller wrote:
> >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. (-:
> >
> _______________________________________________
> Python mailing list
> Python at euglug.org
> http://www.euglug.org/mailman/listinfo/python

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


More information about the Python mailing list