I have a memory heavy class, say a type representing a high-resolution resource (ie: media, models, data, etc), that can be instantiated multiple times with identical parameters, such as same filename of the resource loaded multiple times.
I'd like to implement some sort of unbounded caching on object creation to memory reuse identical instances if they have the same constructor parameter values. I don't care about mutability of one instance affecting the other shared ones. What is the easiest pythonic way to achieve this?
Note that neither singletons, object-pools, factory methods or field properties meet my use case.
You could use a factory function with functools.cache:
EDIT: Apparently you can decorate your class directly to get the same effect:
Note the same memory address both times
Foo(1)is called.Edit 2: After some playing around, you can get your default-respecting instance cache behavior if you override
__new__and do all of your caching and instantiation there:output:
The
__init__will still be called after__new__, so you will want to do your expensive initialization (or all of it) in__new__after the cache check.