Singleton across modules

旧时模样 提交于 2019-12-21 20:15:01

问题


I'm trying to implement a Singleton and I am running into difficulty when I import the module. My set up is the following. I am using Python 2.7.

MODULE 1

class SingletonClass(object):
    def __new__(self, *args, **kwargs):
        if not self._instance:
            self._instance = super(SingletonClass, self).__new__(
                                self, *args, **kwargs)
        return self._instance

print SingletonClass()  #OUTPUT: 0x00000000030F1630
print SingletonClass()  #OUTPUT: 0x00000000030F1630 (Good, what I want)

MODULE 2

import SingletonClass

class AnotherClass:
    print SingletonClass.SingletonClass() #OUTPUT: 0x0000000003292208

Within the module the singleton is working, but in another module the Singleton is not returning the same object as it did in the first. Any idea why?

Edit

For now I will put the only thing that I have found that works. I'm sure there is a better solution to this, but I think this may better convey what the underlying problem is.

MODULE 1

class SingletonParent(object):
    _instance = None

    def __new__(self, *args, **kwargs):
        if not self._instance:
            self._instance = super(SingletonParent, self).__new__(
                                self, *args, **kwargs)
        return self._instance

MODULE 2

import SingletonParent    
class SingletonClass(object):
        def __new__(self, *args, **kwargs):
            if not SingletonParent.SingletonParent._instance:
               SingletonParent.SingletonParent._instance = super(SingletonClass, self).__new__(
                            self, *args, **kwargs)
            return SingletonParent.SingletonParent._instance 

    print SingletonClass()  #OUTPUT: 0x00000000030F1630
    print SingletonClass()  #OUTPUT: 0x00000000030F1630

MODULE 3

import SingletonClass

class AnotherClass:
    print SingletonClass.SingletonClass() #OUTPUT: 0x00000000030F1630

Solution (Edit 3)

Lesson: Don't have your main function in the same module as your Singleton!


回答1:


Your problem is most likely that the module is being imported twice under two different names.

To test for this, add something like:

print "Being imported..."

In module1.py.

If this message is printed twice, then the module is being imported twice, and that's your problem. To fix it, make sure that you're using the same name to import the module everywhere[0], and that you're not doing hackery with sys.path.

[0]: Technically this shouldn't be necessary, but it's a simple fix.



来源:https://stackoverflow.com/questions/10984697/singleton-across-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!