Python doesn't have private constructors, but for this purpose, we can use the __new__ class method to ensure that only one instance is ever created:
class OneOnly: _singleton = None def __new__(cls, *args, **kwargs): if not cls._singleton: cls._singleton = super(OneOnly, cls ).__new__(cls, *args, **kwargs) return cls._singleton
When __new__ is called, it normally constructs a new instance of that class. When we override it, we first check whether our singleton instance has been created; if not, we create it using a super call. Thus, whenever we call the constructor on OneOnly, we always get the exact same instance:
>>> o1 = OneOnly() >>> o2 = OneOnly() >>> o1 == o2 True >>> o1 <__main__.OneOnly object at 0xb71c008c> >>> o2 <__main__.OneOnly object at 0xb71c008c>
The two objects are equal and located at the same address; thus, they are the same object. This particular implementation isn't very transparent, since it's not obvious that a singleton object has been created. Whenever we call a constructor, we expect a new instance of that object; in this case, that contract is violated. Perhaps, good docstrings on the class could alleviate this problem if we really think we need a singleton.
But we don't need it. Python coders frown on forcing the users of their code into a specific mindset. We may think only one instance of a class will ever be required, but other programmers may have different ideas. Singletons can interfere with distributed computing, parallel programming, and automated testing, for example. In all those cases, it can be very useful to have multiple or alternative instances of a specific object, even though a normal operation may never require one.