Static caching property

dieter dieter at handshake.de
Tue Mar 22 04:30:03 EDT 2016


"Joseph L. Casale" <jcasale at activenetwerx.com> writes:
> ...
> I need to cache the results of a method on a class across all instances.

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".




More information about the Python-list mailing list