Well, I have never felt the need to use such a thing in Python - and most Python programmers I know did not looked for something like this either. I have the impression that Python objects are lightweight in general and it would be better to create a lot of them and avoid the inherent problems of mutable objects than to use singletons for the sake of optimization.
Anyway, if one really wants some kind of singleton, the usual way is to create a value in a module:
# Module stuff.py
class Stuff(object):
# ....
pass
singleton = new Stuff()
Then you use it:
import stuff
stuff.singleton.do_something()
You can even, let us say, replace the value in the module, as you would do by swapping the applicationContext.xml
files of Spring. It can be useful in tests, for example:
import stuff
stuff.singleton = MockedStuff()
class MyTestCase(TestCase):
def testMockStuff(self):
# Component can be a class which uses the singleton
component = Component()
# Proceed with tests
Actually, you can mock even the whole class:
import stuff
stuff.Stuff = MockedStuff
class MyTestCase(TestCase):
def testMockStuff(self):
# Component creates some instance of stuff.Stuff, which is mocked now
component = Component()
# Proceed with tests
Summarizing: IMHO, Python programmers do not feel the necessity of something like Spring DI. If one needs some functionality of Spring DI, it is easy to implement through pure Python code.
(There are points based in my experience. I am sure more people can point another causes.)