Singleton

OnCallSupport321 at gmail.com OnCallSupport321 at gmail.com
Wed Oct 10 09:34:36 EDT 2007


Spring Python (http://springpython.python-hosting.com) offers a
singleton solution. You can mark up function calls to only be called
the first time, i.e. as singletons. The results are cached inside the
Spring Python IoC container, so the next time the function is called,
it returns the cached copy. Prototypes bypass the caching, and instead
allow the function to be called everytime. This also support the idea
of prototype functions contain references to singleton objects.

from springpython.context import *

class MyContainer(DecoratorBasedApplicationContext):
   def __init__(self):
      DecoratorBasedAppicationContext.__init__(self)

   @component(scope.SINGLETON) # You can leave off the argument, since
scope.SINGLETON is the default)
   def singletonComponent(self):
      return ["There can be only one!"]

   @component(scope.PROTOTYPE):
   def prototypeComponent(self):
      return ["I think I'm a clone now. There's another one of me
always hangin' around!"]

if __name__ == "__main__":
   appContext = MyContainer()

   obj1 = appContext.singletonComponent()
   obj2 = appContext.singletonComponent()
   if obj1 == obj2:
      print "These are the same object"
   else:
      print "Something is wrong!"

   obj3 = appContext.prototypeComponent()
   obj4 = appContext.prototypeComponent()
   if obj1 != obj2:
      print "These are different instances of the function call."
   else:
      print "These shouldn't be the same!"

See also http://springpython.python-hosting.com/wiki/InversionOfControl
and http://springpython.python-hosting.com/wiki/DecoratorBasedApplicationContext.




More information about the Python-list mailing list