|
| 1 | +""" |
| 2 | +Declarative objects. |
| 3 | +
|
| 4 | +Declarative objects have a simple protocol: you can use classes in |
| 5 | +lieu of instances and they are equivalent, and any keyword arguments |
| 6 | +you give to the constructor will override those instance variables. |
| 7 | +(So if a class is received, we'll simply instantiate an instance with |
| 8 | +no arguments). |
| 9 | +
|
| 10 | +You can provide a variable __unpackargs__ (a list of strings), and if |
| 11 | +the constructor is called with non-keyword arguments they will be |
| 12 | +interpreted as the given keyword arguments. |
| 13 | +
|
| 14 | +If __unpackargs__ is ('*', name), then all the arguments will be put |
| 15 | +in a variable by that name. |
| 16 | +
|
| 17 | +You can define a __classinit__(cls, new_attrs) method, which will be |
| 18 | +called when the class is created (including subclasses). Note: you |
| 19 | +can't use super() in __classinit__ because the class isn't bound to a |
| 20 | +name. As an analog to __classinit__, Declarative adds |
| 21 | +__instanceinit__ which is called with the same argument (new_attrs). |
| 22 | +This is like __init__, but after __unpackargs__ and other factors have |
| 23 | +been taken into account. |
| 24 | +
|
| 25 | +If __mutableattributes__ is defined as a sequence of strings, these |
| 26 | +attributes will not be shared between superclasses and their |
| 27 | +subclasses. E.g., if you have a class variable that contains a list |
| 28 | +and you append to that list, changes to subclasses will effect |
| 29 | +superclasses unless you add the attribute here. |
| 30 | +
|
| 31 | +Also defines classinstancemethod, which acts as either a class method |
| 32 | +or an instance method depending on where it is called. |
| 33 | +""" |
| 34 | + |
| 35 | +from __future__ import generators |
| 36 | + |
| 37 | +__all__ = ('classinstancemethod', 'DeclarativeMeta', 'Declarative') |
| 38 | + |
| 39 | +import copy |
| 40 | + |
| 41 | +try: |
| 42 | + import itertools |
| 43 | + counter = itertools.count() |
| 44 | +except ImportError: |
| 45 | + def _counter(): |
| 46 | + i = 0 |
| 47 | + while 1: |
| 48 | + i += 1 |
| 49 | + yield i |
| 50 | + counter = _counter() |
| 51 | + |
| 52 | +class classinstancemethod(object): |
| 53 | + """ |
| 54 | + Acts like a class method when called from a class, like an |
| 55 | + instance method when called by an instance. The method should |
| 56 | + take two arguments, 'self' and 'cls'; one of these will be None |
| 57 | + depending on how the method was called. |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self, func): |
| 61 | + self.func = func |
| 62 | + |
| 63 | + def __get__(self, obj, type=None): |
| 64 | + return _methodwrapper(self.func, obj=obj, type=type) |
| 65 | + |
| 66 | +class _methodwrapper(object): |
| 67 | + |
| 68 | + def __init__(self, func, obj, type): |
| 69 | + self.func = func |
| 70 | + self.obj = obj |
| 71 | + self.type = type |
| 72 | + |
| 73 | + def __call__(self, *args, **kw): |
| 74 | + assert not kw.has_key('self') and not kw.has_key('cls'), ( |
| 75 | + "You cannot use 'self' or 'cls' arguments to a " |
| 76 | + "classinstancemethod") |
| 77 | + return self.func(*((self.obj, self.type) + args), **kw) |
| 78 | + |
| 79 | + def __repr__(self): |
| 80 | + if self.obj is None: |
| 81 | + return ('<bound class method %s.%s>' |
| 82 | + % (self.type.__name__, self.func.func_name)) |
| 83 | + else: |
| 84 | + return ('<bound method %s.%s of %r>' |
| 85 | + % (self.type.__name__, self.func.func_name, self.obj)) |
| 86 | + |
| 87 | + |
| 88 | +class DeclarativeMeta(type): |
| 89 | + |
| 90 | + def __new__(meta, class_name, bases, new_attrs): |
| 91 | + cls = type.__new__(meta, class_name, bases, new_attrs) |
| 92 | + if new_attrs.has_key('__classinit__'): |
| 93 | + cls.__classinit__ = staticmethod(cls.__classinit__.im_func) |
| 94 | + cls.declarative_count = counter.next() |
| 95 | + cls.__classinit__(cls, new_attrs) |
| 96 | + return cls |
| 97 | + |
| 98 | +class Declarative(object): |
| 99 | + |
| 100 | + __unpackargs__ = () |
| 101 | + |
| 102 | + __mutableattributes__ = () |
| 103 | + |
| 104 | + __metaclass__ = DeclarativeMeta |
| 105 | + |
| 106 | + def __classinit__(cls, new_attrs): |
| 107 | + for name in cls.__mutableattributes__: |
| 108 | + if not new_attrs.has_key(name): |
| 109 | + setattr(cls, copy.copy(getattr(cls, name))) |
| 110 | + |
| 111 | + def __instanceinit__(self, new_attrs): |
| 112 | + for name, value in new_attrs.items(): |
| 113 | + setattr(self, name, value) |
| 114 | + if not new_attrs.has_key('declarative_count'): |
| 115 | + self.declarative_count = counter.next() |
| 116 | + |
| 117 | + def __init__(self, *args, **kw): |
| 118 | + if self.__unpackargs__ and self.__unpackargs__[0] == '*': |
| 119 | + assert len(self.__unpackargs__) == 2, \ |
| 120 | + "When using __unpackargs__ = ('*', varname), you must only provide a single variable name (you gave %r)" % self.__unpackargs__ |
| 121 | + name = self.__unpackargs__[1] |
| 122 | + if kw.has_key(name): |
| 123 | + raise TypeError( |
| 124 | + "keyword parameter '%s' was given by position and name" |
| 125 | + % name) |
| 126 | + kw[name] = args |
| 127 | + else: |
| 128 | + if len(args) > len(self.__unpackargs__): |
| 129 | + raise TypeError( |
| 130 | + '%s() takes at most %i arguments (%i given)' |
| 131 | + % (self.__class__.__name__, |
| 132 | + len(self.__unpackargs__), |
| 133 | + len(args))) |
| 134 | + for name, arg in zip(self.__unpackargs__, args): |
| 135 | + if kw.has_key(name): |
| 136 | + raise TypeError( |
| 137 | + "keyword parameter '%s' was given by position and name" |
| 138 | + % name) |
| 139 | + kw[name] = arg |
| 140 | + if kw.has_key('__alsocopy'): |
| 141 | + for name, value in kw['__alsocopy'].items(): |
| 142 | + if not kw.has_key(name): |
| 143 | + if name in self.__mutableattributes__: |
| 144 | + value = copy.copy(value) |
| 145 | + kw[name] = value |
| 146 | + del kw['__alsocopy'] |
| 147 | + self.__instanceinit__(kw) |
| 148 | + |
| 149 | + def __call__(self, *args, **kw): |
| 150 | + kw['__alsocopy'] = self.__dict__ |
| 151 | + return self.__class__(*args, **kw) |
| 152 | + |
| 153 | + def singleton(self, cls): |
| 154 | + if self: |
| 155 | + return self |
| 156 | + name = '_%s__singleton' % cls.__name__ |
| 157 | + if not hasattr(cls, name): |
| 158 | + setattr(cls, name, cls(declarative_count=cls.declarative_count)) |
| 159 | + return getattr(cls, name) |
| 160 | + singleton = classinstancemethod(singleton) |
| 161 | + |
| 162 | + def __repr__(self, cls): |
| 163 | + if self: |
| 164 | + name = '%s object' % self.__class__.__name__ |
| 165 | + v = self.__dict__.copy() |
| 166 | + else: |
| 167 | + name = '%s class' % cls.__name__ |
| 168 | + v = cls.__dict__.copy() |
| 169 | + if v.has_key('declarative_count'): |
| 170 | + name = '%s %i' % (name, v['declarative_count']) |
| 171 | + del v['declarative_count'] |
| 172 | + # @@: simplifying repr: |
| 173 | + #v = {} |
| 174 | + names = v.keys() |
| 175 | + args = [] |
| 176 | + for n in self._repr_vars(names): |
| 177 | + args.append('%s=%r' % (n, v[n])) |
| 178 | + if not args: |
| 179 | + return '<%s>' % name |
| 180 | + else: |
| 181 | + return '<%s %s>' % (name, ' '.join(args)) |
| 182 | + |
| 183 | + def _repr_vars(dictNames): |
| 184 | + names = [n for n in dictNames |
| 185 | + if not n.startswith('_') |
| 186 | + and n != 'declarative_count'] |
| 187 | + names.sort() |
| 188 | + return names |
| 189 | + _repr_vars = staticmethod(_repr_vars) |
| 190 | + |
| 191 | + __repr__ = classinstancemethod(__repr__) |
| 192 | + |
0 commit comments