Advertisement
rfmonk

singleton_ex.py

Oct 6th, 2014
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.13 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. The desired properties of the Singleton pattern can be encapsulated
  5. in Python by defining a module, containing module level variables and
  6. functions. To use this modular Singleton, client code merely imports
  7. the module to access its attributes and functions in the normal manner.
  8. This sidesteps many of the wrinkles in the explicitly-coded versions
  9. below and has the singular advantage of requiring zero lines of code
  10. to implement. According to influential Python programmer Alex Martelli.
  11.  
  12. this was forked for study from wikibooks computer science design patterns
  13. """
  14. class Borg:
  15.     __shared_state = {}
  16.     def __init__(self):
  17.         self.__dict__ = self.__shared_state
  18.     # and whatever else is needed in the class
  19.  
  20. """With the new style class, this is a better solution
  21. """
  22.  
  23. class Singleton (object):
  24.     def __new__(cls, *args, **kwargs):
  25.         if not hasattr(cls, 'self'):
  26.             cls.self = object.__new__(cls)
  27.             return cls.self
  28.  
  29. # Usage
  30. mySingleton1 = Singleton()
  31. mySingleton2 = Singleton()
  32.  
  33. # mySingleton1 and mySingleton2 are the same instance.
  34. assert mySingleton1 is mySingleton2
  35.  
  36. """ Two caveats:
  37.    The __init__-method is called everytime Singleton() is called,
  38.    unless cls.__init__ is set to an empty function.
  39.    If it is needed to inherit from the Singleton class, instance should
  40.    probably be the dictionary belonging explicitly to the Singleton
  41.    class.
  42. """
  43. class InheritableSingleton (object):
  44.     instances = {}
  45.     def __new__(cls, *args, **kwargs):
  46.         if InheritableSingleton.instances.get(cls) is None:
  47.             cls.__original_init__ = cls.__init__
  48.             InheritableSingleton.instances[cls] = object.__new__\
  49.                     (cls, *args, **kwargs)
  50.         elif cls.__init__ == cls.__original_init__:
  51.             def nothing(*args, **kwargs):
  52.                 pass
  53.             cls.__init__ = nothing
  54.         return InheritableSingleton.instances[cls]
  55.  
  56. # To create a singleton that inherits from a non-singlton
  57. # multiple inheritance must be used.
  58.  
  59. class Singleton (NonSingletonClass, object):
  60.     instance = None
  61.     def __new__(cls, *args, **kwargs):
  62.         if cls.instance is None:
  63.             cls.instance = object.__new__(cls, *args, **kwargs)
  64.         return cls.instance
  65.  
  66. # Be sure to call the NonSingletonClass's __init__ function from
  67. # the Singletons __init__ function. A more elegant approach using m
  68. # using metaclasses was also suggested
  69.  
  70. class SingletonType(type):
  71.     def __call__(cls):
  72.         if getattr(cls, '__instance__', None) is None:
  73.             instance = cls.__new__(cls)
  74.             instance.__init__()
  75.             cls.__instance__ = instance
  76.         return cls.__instance__
  77.  
  78. # Usage
  79. class Singleton(object):
  80.     __metaclass__ = SingletonType
  81.     def __init__(self):
  82.         print '__init__:', self
  83.  
  84. class OtherSingleton(object):
  85.     __metaclass__ = SingletonType
  86.     def __init__(self):
  87.         print 'OtherSingleton __init__:', self
  88.  
  89. # Tests
  90. s1 = mySingleton1()
  91. s2 = mySingleton2()
  92. assert s1
  93. assert s2
  94. assert s1 is s2
  95. os1 = OtherSingleton()
  96. os2 = OtherSingleton()
  97. assert os1
  98. assert os2
  99. assert os1 is os2
  100.  
  101. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement