1

If I have a class named Foo, then normally a call using syntax Foo() constructs a new instance and initializes it using the __init__ (method/function). I would like a slightly different (optimized) behavior. I would like to memoize the instances according to the arguments of Foo(...) and if ever the same arguments are given, then return the same/identical instance as before, otherwise continue with the default construction protocol. I'll need of course to somewhere implement a cache to memoize the object. I could put that cache in a global variable or even in a property on the class itself.

But does the Python object system allow me to do this?

As I understand __init__ CANNOT be used for this purpose as its return value is ignored by the system.

Of course, one way of course is to never call Foo() directly in my code, but always call makeFoo, but please note that that is not my question. This would be pretty awkward because my program has a hierarchy of such classes, only some of which are memorable. I don't want to make this different visible to the application programmer.

Jim Newton
  • 594
  • 3
  • 16
  • 2
    Well, most importantly, check out `__new__` and `lru_cache`. – Captain Trojan Jun 27 '21 at 09:52
  • 1
    Thanks for the hints. BTW I did indeed spend *a fraction of the time* as you suggested investigating. But I kept falling on information about `__init__` and people calling it a constructor, when it is it no really a constructor, but an initializer. – Jim Newton Jun 27 '21 at 10:12

0 Answers0