I have several classes that are widespread in my Python application and which should only have one global instance (e.g. Logger, DbConnection). Python does not support static variables / methods in a class, so the usual Java / C ++ way of creating a singleton does not work here. I was looking for alternatives to implement singleton in Python. I want a simple (without metaprogramming, if possible) and clean implementation. It looks good:
class MyClass(object): def a(): pass singleton = MyClass()
Using a singleton would be as simple as
import myClass myClass.singleton.a()
The direct assignment can be replaced by the create function if the initialization of the object is not so simple.
I could also create getInstance () in the module area and always use it to get myObj.
Question 1) Does it work fine? Module code (destination myObj) is only triggered the first time I enter any other module, and myObj will not be generated every time I import this module somewhere?
An alternative method I've seen is to use the global module. Sort of:
from myClass1 import MyClass1 from myClass2 import MyClass2 myObj1 = MyClass1() myObj2 = MyClass2()
Using this:
import globals globals.myObj1.a()
I prefer the first alternative.
Question 2) Between the two solutions, what do you recommend?
Question 3) The third solution would be to distribute widespread objects, such as Logger, to several classes / functions, but this is not a good imho solution. Is there a better solution not mentioned here?
I know about the disadvantages of using global variables and singletones. However, having a global state is not a big problem in my application. I prefer solutions that have code clarity and are easy to use.