Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Singleton objects with the same attribute

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading