Easy caching

Peter Otten __peter__ at web.de
Thu Nov 13 09:03:35 CET 2008


jalanb3 wrote:

> Evening all,
> 
> And thank you for your valuable reading skills.
> 
> The following pattern turned up in coding tonight.
> It works, but I'm suspicious, it just seems too easy.
> 
> So any comments or constructive criticisms welcome ?
> 
> *** Start doctest format ***
> 
> >>> class Cacher:
> ...     def __init__(self):
> ...         self.value_in_database = 0
> ...
> ...     def very_slow_database_access(self):
> ...         return self.value_in_database
> ...
> ...     @property
> ...     def show(self):
> ...         result = self.very_slow_database_access()
> ...         self.show = result
> ...         return result
> ...

The above only works because properties don't work with classic class. If
you make Cacher a newstyle class (have it inherit from object) you'll get
an AttributeError. Therefore I think it would be cleaner to either 

use __getattr__() or

change the Cacher to something like

class Cacher(object):
    def __init__(self):
        self._show = None
    # ...
    
    @property
    def show(self):
        result = self._show
        if result is None:
            result = self._show = self.very_slow_database_access()
        return result

Peter



More information about the Python-list mailing list