> 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
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to