943,469 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 741
  • Python RSS
2

Singletonize any class

by on Nov 11th, 2009
This is one simple way to emulate a singleton class on behalf of a normal class. (A singleton class is a class with at most one instance.)

The implementation does not emulate a class 100% (for example it lacks the special attributes lile __dict__ or __bases__), but it should be absolutely sufficient in most common cases.
Python Code Snippet (Toggle Plain Text)
  1. def Singleton(cls):
  2. instance = []
  3. def create(*args, **kw):
  4. if not instance:
  5. instance.append(cls(*args, **kw))
  6. return instance[0]
  7. return create
  8.  
  9. # Test:
  10.  
  11. TheList = Singleton(list)
  12.  
  13. def test2():
  14. mylist1 = TheList([1,2,3])
  15. mylist2 = TheList()
  16. print mylist1, mylist2
  17. mylist1.append(4)
  18. del mylist1[1]
  19. print mylist1, mylist2
  20.  
  21. >>> test2()
  22. [1, 2, 3] [1, 2, 3]
  23. [1, 3, 4] [1, 3, 4]
Message:
Previous Thread in Python Forum Timeline: Dictionary Sorting By Values Other Than Keys
Next Thread in Python Forum Timeline: Python - writing to file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC