]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/lib/subclass.py
Make Currency objects (and others using the SuperSubclass) immutable
[bluechips.git] / bluechips / lib / subclass.py
1 """
2 Create subclasses that call out to their "superclass" for all methods
3 but return the "subclass's" type
4 """
5
6 from weakref import WeakValueDictionary
7
8 def wrapper(c, func):
9     return (lambda self,*args: c(getattr(self.value, func)(*map(self.value.__class__, args))))
10
11 def __new__(cls, value=0):
12     if value not in cls.__old_values__:
13         new_object = super(cls, cls).__new__(cls, value)
14         cls.__old_values__[value] = new_object
15         return new_object
16     else:
17         return cls.__old_values__[value]
18
19 class SmartSubclass(object):
20     def __init__(self, superclass, exclude=[]):
21         self.superclass = superclass
22         self.exclude = exclude
23     def __call__(self, name, bases, dict):
24         dict['__old_values__'] = WeakValueDictionary()
25         dict['__new__'] = __new__
26         c = type(name, bases, dict)
27         for func in dir(self.superclass):
28             if func not in dir(c) and \
29                 callable(getattr(self.superclass, func)) and \
30                 func not in self.exclude:
31                 setattr(c, func, wrapper(c, func))
32         return c
33
34 __all__ = ['SmartSubclass']