One way that would be more general than the Django approach, __slots__ and available in python 2, would be this metaclass:
class OrderedTypeMeta(type): def __new__(mcls, clsname, bases, clsdict): attrs = clsdict.get('_attrs_', []) attrnames = [] for name, value in attrs: clsdict[name] = value attrnames.append(name) clsdict['_attrs_'] = attrnames return super(OrderedTypeMeta, mcls).__new__(mcls, clsname, bases, clsdict) class User(DataStructure): __metaclass__ = OrderedTypeMeta _attrs_ = (('name', StringValue()), ('password', StringValue()), ('age', IntegerValue()))
I say this is more general than the django way, because you don't need attributes to be instances of a particular class, any value will do. It is also more general than __slots__ , because you can still assign attributes to class instances (although this might not be necessary: โโin this case, I would prefer __slots__ ). In python3, I would prefer __prepare__ .
The main disadvantage of this, besides being ugly, is that it will not work with inheritance. It would not be too difficult to get __attrs__ from the base classes and extend this, instead of setting it to an empty list.
aaronasterling
source share