Static caching property

Joseph L. Casale jcasale at activenetwerx.com
Tue Mar 22 08:12:20 EDT 2016


> If a method call on any instance defines the return value for
> all instances, then this method likely should be a class method --
> and use a class attribute to store the result -- something like this:
>
>     class C(object):
>
>     _cache = {}
>
>     @classmethod
>     def f(cls, ...):
>       ... determine cache key `key` ...
>       v = cls._cache.get(key)
>       if v is None:
>          v = cls._cache[key] = ...
>       return v
>
> It will work also without the "@classmethod".

Ok, classmethod has advantages when considering OOP, but this is flawed.

Ethan was spot on (aside from the typo in the return statement), if the expensive
API call returns None, since it is a singleton your code will continue to invoke it.

This implementation also invokes additional hashing and lookups.

Ethan's implementation also supports inheritance.

jlc



More information about the Python-list mailing list