When to use Singleton in python?

There are many questions related to using the Singleton pattern in python, and although this question may repeat many of the aspects discussed, I did not find the answer to the following specific question.

Suppose I have a class MyClassthat I want to create only once. In python, I can do this as follows in code myclass.py:

class MyClass(object): 
    def foo(self):
        ....


instance = MyClass()

Then in any other program, I can reference the instance simply with

import myclass
myclass.instance.foo()

Under what circumstances is this approach enough? Under what circumstances is the use of the Singleton pattern useful / mandatory?

+5
source share
3 answers

, . Python , ( clobber !) , singleton: , , ? , ?

, , . , , singleton, singleton .

, "singleton" :

if __name__ == '__main__':
   instance = MyClass()
   doSomethingWith(instance)

"" singleton , , , , module.instance, , MyClass.

+7

, , , , , - ( ). , , instance, , sys.modules :

class _MyClass(object):
    def foo(self):
        print 'foo()'

_MyClass.instance = _MyClass()

import sys
_ref = sys.modules[__name__]  # Reference to current module so it not deleted
sys.modules[__name__] = _MyClass.instance

"" , () - factory, . Python- , , - , sys.modules .

, , , properties - - . , , .

Alex Martelli ActiveState Python.

+3

, .

  • , .
  • , .

( ), .

API, . , - , , , , .

0

All Articles