0

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.

DevZer0
  • 13,433
  • 7
  • 27
  • 51

1 Answers1

5

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • i am reading the configuration from a config file and storing in the class at run time, but i see what your suggesting i could use the class it self to read the variables from config file and have it available. But if i don't use a singleton object it would have to re-read the config file everytime i use it? can you please elaborate more on the Pythonic approach you were suggesting – DevZer0 Jan 15 '14 at 09:32
  • so your saying instead of creating the config file, use a class as the config file it self? – DevZer0 Jan 15 '14 at 09:40