I want Python to return the same object when the instances are created with the similar attributes.
class Session:
def __init__(self, id):
self.id = id
...
...
session1 = Session(1)
print(id(session1)) # 1111
session1a = Session(1)
print(id(session11)) # 1111
session2 = Session(2)
print(id(session1)) # 2222
You can see above that I want session1 and session1a be the same object because of Session(1), while session2 is another object because of Session(2).
How could I do it?
>Solution :
You can override the __new__ method to return a cached object for the same parameters.
A weakref.WeakValueDictionary is an appropriate data structure for storing your cached objects, when objects are deleted they will be garbage collected rather than persisting because your cache references them
from weakref import WeakValueDictionary
class Session:
_cache = WeakValueDictionary()
def __new__(cls, id):
obj = cls._cache.get(id)
if not obj:
obj = object.__new__(cls)
cls._cache[id] = obj
return obj
def __init__(self, id):
self.id = id
The same object will be returned for the same id
s1 = Session(1)
print(id(s1)) # 4532746224
s2 = Session(1)
print(id(s2)) # 4532746224
s3 = Session(2)
print(id(s3)) # 4534405248