Currently I'm using a rather simplistic implementation of a singleton. However, I've never seen anything like this suggested on the web, which leads me to believe there might be something wrong with it...
class Singleton:
def __init__():
raise ...
@staticmethod
def some():
pass
@staticmethod
def another():
pass
Are there any disadvantages to this implementation of a singleton (making all class members static). It is somewhat similar to using modules as singletons, except you wrap everything in a class.
Edit: I know about other ways to implement singletons in Python. What I don't like about them is that none of them are explicit (which goes against the Python zen):
Since I do a = Class()
instead of something like a = Class.Instance()
, it is not obvious that I'm dealing with on object with shared state (see note #1). If all members are static I at least have Class.someMethod()
which kinda sorta suggests it's a singleton. What I don't like about this approach is that you can't use constructors and destructors, which removes the major advantage that singletons have over free functions, which is what you can do when they are created and destroyed (see note #2).
Note #1: I know I shouldn't care about the singleton's state (if I do, then it shouldn't be a singleton in the first place). I still want it to be explicit about what kind of class it is.
Note #2: When you create a singleton you could do some instantiation in its constructor. For example, in a singleton that deals with the graphics library, you could initialize the library in the constrctor. This way instantiation and deinstantiation happen automatically in the sinleton's constructors and destructor.
Or in a ResourceManager: the destructor could check if upon its destruction there still are resources in memory and act accordingly.
If you use free functions instead of singletons you have to do all of this by hand.