python - Setup dictionary lazily -
let's have dictionary in python, defined @ module level (mysettings.py
):
settings = { 'expensive1' : expensive_to_compute(1), 'expensive2' : expensive_to_compute(2), ... }
i values computed when keys accessed:
from mysettings import settings # settings "prepared" print settings['expensive1'] # value computed.
is possible? how?
if don't separe arguments callable, don't think it's possible. however, should work:
class mysettingsdict(dict): def __getitem__(self, item): function, arg = dict.__getitem__(self, item) return function(arg) def expensive_to_compute(arg): return arg * 3
and now:
>>> settings = mysettingsdict({ 'expensive1': (expensive_to_compute, 1), 'expensive2': (expensive_to_compute, 2), }) >>> settings['expensive1'] 3 >>> settings['expensive2'] 6
edit:
you may want cache results of expensive_to_compute
, if accessed multiple times. this
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
and now:
>>> settings.values() dict_values([(<function expensive_to_compute @ 0x9b0a62c>, 2), (<function expensive_to_compute @ 0x9b0a62c>, 1)]) >>> settings['expensive1'] 3 >>> settings.values() dict_values([(<function expensive_to_compute @ 0x9b0a62c>, 2), 3])
you may want override other dict
methods depending of how want use dict.
Comments
Post a Comment