singleton objects with decorators

Michele Simionato michele.simionato at gmail.com
Tue Apr 12 11:00:42 EDT 2005


I did not put memoize on __new__. I put it on the metaclass __call__.
Here is my memoize:

 def memoize(func):
     memoize_dic = {}
     def wrapped_func(*args):
         if args in memoize_dic:
             return memoize_dic[args]
         else:
             result = func(*args)
             memoize_dic[args] = result
             return result
     wrapped_func.__name__ = func.__name__
     wrapped_func.__doc__ = func.__doc__
     wrapped_func.__dict__ = func.__dict__
     return wrapped_func

 class Memoize(type): # Singleton is a special case of Memoize
     @memoize
     def __call__(cls, *args):
         return super(Memoize, cls).__call__(*args)




More information about the Python-list mailing list