Python __missing__

According to the python documentation:


If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable.


For an example, see collections.defaultdict.


This is, at least, incomplete, since __missing__ must not only return the default value, but also assign it internally. This is made clear in the documentation for collections.defaultdict:


If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

Surprisingly, the __missing__ method is not mentioned in the special method names section of the python documentation.

class memoize(dict):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args):
        print "__call__"
        return self[args]

    def __missing__(self, key):
        print "__missing__"
        result = self[key] = self.func(*key)
        return result

@memoize
def foo(a, b):
    return a * b

print foo(1,2)
print foo(1,2)
print foo(1,2)
print foo(1,2)
print foo(1,2)
print foo(1,2)

执行结果:

__call__
__missing__
2
__call__
2
__call__
2
__call__
2
__call__
2
__call__
2



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值