adding a static class to another class

James Stroud jstroud at mbi.ucla.edu
Mon Sep 17 04:08:43 EDT 2007


James Stroud wrote:
> Nathan Harmston wrote:
>> And also preventing more than one Manager instance instantiated at one
>> time.
> 
> Forgot to answer this. You want the singleton pattern:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558

But not really a singleton now that I think about it...

class Singletonish(object):
     """ A python singletonish """

     class __impl(object):
         """ Implementation of the singletonish interface """

         def spam(self):
             """ Test method, return singletonish id """
             return id(self)

     # storage for the instance reference
     __instance = None

     def __init__(self):
         """ Create singletonish instance """
         Singletonish.__instance = Singletonish.__impl()

     def __getattr__(self, attr):
         """ Delegate access to implementation """
         if attr == '__id__':
           return id(Singletonish.__instance)
         return getattr(Singletonish.__instance, attr)

     def __setattr__(self, attr, value):
         """ Delegate access to implementation """
         return setattr(Singletonish.__instance, attr, value)


In action:

py> class Singletonish(object):
...     """ A python singletonish """
...     class __impl(object):
...         """ Implementation of the singletonish interface """
...         def spam(self):
...             """ Test method, return singletonish id """
...             return id(self)
...     # storage for the instance reference
...     __instance = None
...     def __init__(self):
...         """ Create singletonish instance """
...         Singletonish.__instance = Singletonish.__impl()
...     def __getattr__(self, attr):
...         """ Delegate access to implementation """
...         return getattr(Singletonish.__instance, attr)
...     def __setattr__(self, attr, value):
...         """ Delegate access to implementation """
...         return setattr(Singletonish.__instance, attr, value)
...
py> s = Singletonish()
py> print s.spam()
18727248
py>
py> t = Singletonish()
py> print t.spam()
18682480
py> print s.spam()
18682480


Of course t and s are not /really/ the same:


py> print id(t)
18727056
py> print id(s)
18727280
py> assert t is s
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.AssertionError'>


But this shouldn't matter unless you have a special use case because the 
implementation to all Singletonish objects are delegated to to the 
latest __impl object and so behave identically.

James



More information about the Python-list mailing list