The following class shows how to implement the singleton pattern in Python. A singleton is a class that makes sure only one instance of it is ever created. Typically such classes are used to manage resources that by their very nature can only exist once.
Python, 42 lines
This implementation hides the singleton interface in an inner class and creates exactly one instance of the inner class. The outer class is a handle to the inner class and delegates any requests to it. While the id() of the handle objects changes, the id() of the inner class which implements the singleton behaviour is constant.
Of course, the inner class is not REALLY hidden, like anything in Python. But you have to invest extra effort to break into the singleton.
This is related to the "Automatic delegation as an alternative to inheritance" recipe.
 Gamma, Helm, et al, "Design Patterns - Elements of Reusable Object-Oriented Software". Addison-Wesley, 1995, ISBN 0-201-63361-2.