""" Declarative objects. Declarative objects have a simple protocol: you can use classes in lieu of instances and they are equivalent, and any keyword arguments you give to the constructor will override those instance variables. (So if a class is received, we'll simply instantiate an instance with no arguments). You can provide a class variable ``__unpackargs__`` (a list of strings), and if the constructor is called with non-keyword arguments they will be interpreted as the given keyword arguments. If ``__unpackargs__`` is ``('*', name)``, then all the arguments will be put in a variable by that name. You can define a ``__classinit__(cls, new_attrs)`` method, which will be called when the class is created (including subclasses). Note: you can't use ``super()`` in ``__classinit__`` because the class isn't bound to a name. As an analog to ``__classinit__``, ``Declarative`` adds ``__instanceinit__`` which is called with the same argument (``new_attrs``). This is like ``__init__``, but applied after ``__unpackargs__`` and other factors have been taken into account. If ``__mutableattributes__`` is defined as a sequence of strings, these attributes will not be shared between superclasses and their subclasses. E.g., if you have a class variable that contains a list and you append to that list, changes to subclasses will effect superclasses unless you add the attribute here. So any variables listed there will be copied (shallowly). """ from __future__ import generators import copy from classinst import classinstancemethod from eventhub import EventHub import sys __all__ = ('DeclarativeMeta', 'Declarative') try: import itertools counter = itertools.count() except ImportError: def _counter(): i = 0 while 1: i += 1 yield i counter = _counter() class DeclarativeMeta(type): def __new__(meta, class_name, bases, new_attrs): post_funcs = [] early_funcs = [] #events.send(events.ClassCreateSignal, # bases[0], class_name, bases, new_attrs, # post_funcs, early_funcs) cls = type.__new__(meta, class_name, bases, new_attrs) for func in early_funcs: func(cls) if new_attrs.has_key('__classinit__'): cls.__classinit__ = staticmethod(cls.__classinit__.im_func) cls.__classinit__(cls, new_attrs) for func in post_funcs: func(cls) return cls class Declarative(object): __unpackargs__ = () __mutableattributes__ = () __metaclass__ = DeclarativeMeta __restrict_attributes__ = None def __classinit__(cls, new_attrs): cls.declarative_count = counter.next() for name in cls.__mutableattributes__: if not new_attrs.has_key(name): setattr(cls, copy.copy(getattr(cls, name))) def __instanceinit__(self, new_attrs): if self.__restrict_attributes__ is not None: for name in new_attrs: if name not in self.__restrict_attributes__: raise TypeError( '%s() got an unexpected keyword argument %r' % (self.__class__.__name__, name)) for name, value in new_attrs.items(): setattr(self, name, value) if not new_attrs.has_key('declarative_count'): self.declarative_count = counter.next() def __init__(self, *args, **kw): if self.__unpackargs__ and self.__unpackargs__[0] == '*': assert len(self.__unpackargs__) == 2, \ "When using __unpackargs__ = ('*', varname), you must only provide a single variable name (you gave %r)" % self.__unpackargs__ name = self.__unpackargs__[1] if kw.has_key(name): raise TypeError( "keyword parameter '%s' was given by position and name" % name) kw[name] = args else: if len(args) > len(self.__unpackargs__): raise TypeError( '%s() takes at most %i arguments (%i given)' % (self.__class__.__name__, len(self.__unpackargs__), len(args))) for name, arg in zip(self.__unpackargs__, args): if kw.has_key(name): raise TypeError( "keyword parameter '%s' was given by position and name" % name) kw[name] = arg if kw.has_key('__alsocopy'): for name, value in kw['__alsocopy'].items(): if not kw.has_key(name): if name in self.__mutableattributes__: value = copy.copy(value) kw[name] = value del kw['__alsocopy'] self.__instanceinit__(kw) def __call__(self, *args, **kw): kw['__alsocopy'] = self.__dict__ return self.__class__(*args, **kw) def singleton(self, cls): if self: return self name = '_%s__singleton' % cls.__name__ if not hasattr(cls, name): setattr(cls, name, cls(declarative_count=cls.declarative_count)) return getattr(cls, name) singleton = classinstancemethod(singleton) def __repr__(self, cls): if self: name = '%s object' % self.__class__.__name__ v = self.__dict__.copy() else: name = '%s class' % cls.__name__ v = cls.__dict__.copy() if v.has_key('declarative_count'): name = '%s %i' % (name, v['declarative_count']) del v['declarative_count'] # @@: simplifying repr: #v = {} names = v.keys() args = [] for n in self._repr_vars(names): args.append('%s=%r' % (n, v[n])) if not args: return '<%s>' % name else: return '<%s %s>' % (name, ' '.join(args)) def _repr_vars(dictNames): names = [n for n in dictNames if not n.startswith('_') and n != 'declarative_count'] names.sort() return names _repr_vars = staticmethod(_repr_vars) __repr__ = classinstancemethod(__repr__) def setup_attributes(cls, new_attrs): also_set = getattr(cls, '__addtosubclass__', [])[:] cls.__addtosubclass__ = [] items = new_attrs.items() items.sort(declarative_compare) to_set = [] for name, value in items: if name in also_set: also_set.remove(name) if hasattr(value, '__addtoclass__'): to_set.append((name, value)) mro = cls.__mro__ early_to_set = [] for name in also_set: for superclass in mro: if name in superclass.__dict__: obj = superclass.__dict__[name] break else: continue if obj is not None: early_to_set.append((name, obj)) for name, obj in early_to_set + to_set: obj.__addtoclass__(cls, name) def declarative_compare(a, b): return cmp((getattr(a[1], 'declarative_count', sys.maxint), a[0]), (getattr(b[1], 'declarative_count', sys.maxint), b[0]))