In Python, how is it possible to reuse existing equal immutable objects (like is done for str)? Can this be done just by defining a __hash__ method, or does it require more complicated measures?
In Python, how is it possible to reuse existing equal immutable objects (like is
Share
If you want to create via the class constructor and have it return a previously created object then you will need to provide a
__new__method (because by the time you get to__init__the object has already been created).Here is a simple example – if the value used to initialise has been seen before then a previously created object is returned rather than a new one created:
Note that for this example you can use anything to initialise as long as it’s hashable. And just to show that objects really are being reused: