Here is my problem. I have created a pretty heavy readonly class making many database calls with a static “factory” method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exists.
If something was found, the method will just return it. No problem. But if not, how may I create an instance of the object, in a way that works with inheritance?
>>> class A(Object):
>>> @classmethod
>>> def get_cached_obj(self, some_identifier):
>>> # Should do something like `return A(idenfier)`, but in a way that works
>>> class B(A):
>>> pass
>>> A.get_cached_obj('foo') # Should do the same as A('foo')
>>> A().get_cached_obj('foo') # Should do the same as A('foo')
>>> B.get_cached_obj('bar') # Should do the same as B('bar')
>>> B().get_cached_obj('bar') # Should do the same as B('bar')
Thanks.
Because a
WeakValueDictionaryis used, the objects will remain cached as long as you have any other reference to them, and you can callSomeClass.get_obj(identifier)as many times as you like to get that same object. If I’ve understood you correctly, it’s thecls(identifier)which will hit the database and that’s what you want to call less frequently (since you know the objects are immutable.)If you want to keep objects in the cache even if they are no longer referenced elsewhere, then change the
WeakValueDictionaryinto a normal dict.This requires that identifier is suitable for a dict key, and if it’s a string (as you have in your example code) then it is.