osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python3.7 singleton is not unique anymore


Using the following code in Python3.7 doesn't make FOO to be singleton anymore.

import sys

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

if sys.version_info.major == 2:              
    class FOO():
        __metaclass__ = Singleton
        def __init__(self):
            self.id = None
            
        def setid(self, id):
            self.id = id
            
        def getid(self):
            return self.id
else:
    class FOO():
        def __init__(self, metaclass=Singleton):
            self.id = None
            
        def setid(self, id):
            self.id = id
            
        def getid(self):
            return self.id


x1 = FOO()
x1.setid(1)
x2 = FOO()
x2.setid(2)
x = x1
y = FOO()

print(x1, x1.id)
print(x2, x2.id)
print(x, x.id)
print(y, y.id)

python2 results in something like

<__main__.FOO object at 0x0000000007D9C978>, 2
<__main__.FOO object at 0x0000000007D9C978>, 2
<__main__.FOO object at 0x0000000007D9C978>, 2
<__main__.FOO object at 0x0000000007D9C978>, 2

whereas python3.7 result in
<__main__.FOO object at 0x00000000072C2EB8> 1
<__main__.FOO object at 0x0000000007357080> 2
<__main__.FOO object at 0x00000000072C2EB8> 1
<__main__.FOO object at 0x00000000072C2160> None

What did I miss?

Thank you
Eren