Suppose I want to create instances of my class freely, but if I instantiate with the same argument, I want to get the same unique instance representing that argument. For example:
a = MyClass('Instance 1');
b = MyClass('Instance 2');
c = MyClass('Instance 1');
I would want a == c
to be True
, based on the unique identifier I passed in.
Note:
(1) I'm not talking about manipulating the equality operator-- I want a
to really be the same instance as c
.
(2) This is intended as library code, so uniqueness has to be enforced-- we can't just count on users doing the right thing (whatever that is).
Is there a canonical way of achieving this? I run into this pattern all the time, but I usually see solutions involving shadow classes, meant for only internal instantiation. I think I have a cleaner solution, but it does involve a get() method, and I'm wondering if I can do better.