[Python-ideas] caching properties

Arnaud Delobelle arnodel at googlemail.com
Thu Apr 30 21:26:44 CEST 2009


On 30 Apr 2009, at 20:22, Scott David Daniels wrote:

> Steven D'Aprano wrote:
>> Here's a quick&dirty but working solution. (Tested under Python 2.5.)
>> def once(func):
>>    class Cache(object):
>>        def __call__(self, *args, **kwargs):
>>            try:
>>                return self._value
>>            except AttributeError:
>>                result = func(*args, **kwargs)
>>                self._value = result
>>                return result
>>        def expire(self):
>>            del self._value
>>    return Cache()
>
> This is slightly better (name change as in Antoine Pitrou's comment):
>
>    class cached(object):
>
>        def __init__(self, function):
>            self._function = function
>            self._cache = {}
>
>        def __call__(self, *args):
>            try:
>                return self._cache[args]
>            except KeyError:
>                self._cache[args] = self._function(*args)
>                return self._cache[args]
>
>        def expire(self, *args):
>            del self._cache[args]

You're going to run into trouble with unhashable args.

-- 
Arnaud




More information about the Python-ideas mailing list