懒惰地设置词典
问题描述
假设我有一个在模块级别(mysettings.py
)定义的python词典:
settings = {
'expensive1' : expensive_to_compute(1),
'expensive2' : expensive_to_compute(2),
...
}
我希望在访问密钥时计算这些值:
from mysettings import settings # settings is only "prepared"
print settings['expensive1'] # Now the value is really computed.
这可能吗?如何?
解决方案
如果不将参数与Callable分开,我认为这是不可能的。但是,这应该是可行的:
class MySettingsDict(dict):
def __getitem__(self, item):
function, arg = dict.__getitem__(self, item)
return function(arg)
def expensive_to_compute(arg):
return arg * 3
现在:
>>> settings = MySettingsDict({
'expensive1': (expensive_to_compute, 1),
'expensive2': (expensive_to_compute, 2),
})
>>> settings['expensive1']
3
>>> settings['expensive2']
6
编辑:
如果要多次访问expensive_to_compute
的结果,您可能还希望缓存这些结果。大概是这样的
class MySettingsDict(dict):
def __getitem__(self, item):
value = dict.__getitem__(self, item)
if not isinstance(value, int):
function, arg = value
value = function(arg)
dict.__setitem__(self, item, value)
return value
现在:
>>> settings.values()
dict_values([(<function expensive_to_compute at 0x9b0a62c>, 2),
(<function expensive_to_compute at 0x9b0a62c>, 1)])
>>> settings['expensive1']
3
>>> settings.values()
dict_values([(<function expensive_to_compute at 0x9b0a62c>, 2), 3])
您可能还希望重写其他dict
方法,具体取决于您希望如何使用词典。
相关文章