Is this pythonic?
Tim Chase
python.list at tim.thechases.com
Wed Nov 23 07:20:49 EST 2016
On 2016-11-23 22:15, Steve D'Aprano wrote:
> On Wed, 23 Nov 2016 08:10 pm, Frank Millman wrote:
> > The class has a getval() method to return the current value.
> >
> > Usually the value is stored in the instance, and can be returned
> > immediately, but sometimes it has to be computed, incurring
> > further database lookups.
>
> This is called memoisation, or caching, and is a perfectly standard
> programming technique. It's not without its traps though: there's a
> famous quote that says there are only two hard problems in
> computing, naming things and cache invalidation.
Fortunately, you can offload some odd edge-cases to the standard
library, no?
from functools import lru_cache
# ...
@lru_cache(maxsize=1)
def getval(...):
return long_computation()
It doesn't cache across multiple instances of the same class, but
does cache multiple calls to the same instance's function:
>>> from functools import lru_cache
>>> class Foo:
... def __init__(self, name):
... self.name = name
... @lru_cache(maxsize=1)
... def getval(self):
... print("Long process")
... return self.name
...
>>> f1 = Foo("f1")
>>> f2 = Foo("f2")
>>> f1.getval()
Long process
'f1'
>>> f1.getval()
'f1'
>>> f2.getval()
Long process
'f2'
>>> f2.getval()
'f2'
-tkc
More information about the Python-list
mailing list