Reputation: 13535
First of all i would like to state that i am fairly new to Python programming, therefore my approach to solving the problem maybe incorrect, please let me know if that is the case
I am trying to use a Singleton class to store configuration params in my code and use it when needed. I run into an issue that the data stored in the Singleton in the initial creation is not retained in the subsequent calls to the Object.
Maybe the way i create the Singleton object is incorrect, but i was following the code samples that was on SO.
first here is my Singleton class
class Config(object):
__instance = None
dbserver = ""
def __new__(cls):
if cls.__instance == None:
__instance = object.__new__(cls)
__instance.name = "Configuration Object"
return __instance
Here is my initial creation of the Singleton instance
configurator = Config()
configurator.dbserver = dbserver
then subsequently i do the following and dbserver
property returns empty string.
configurator = Config()
print configurator.dbserver
Thanks for your time reading.
Upvotes: 0
Views: 671
Reputation: 599638
You don't seem to be assigning the local variable __instance
to the class variable cls.__instance
.
However, if you're just doing this to store variables, I don't know why you need an instance at all. Just store them directly on the class - which is itself a first-class object in Python - or even use a module, which is more Pythonic.
Edit
Using the class itself wouldn't cause the code to be re-run each time: code at class level is only executed when the class is defined, which happens on first import.
But since the class has to live in a module (a file) somewhere, you could just as easily put all that code directly in the module, and import that where you need it. Again, code at module level is only executed on first import.
Upvotes: 5