inspect.getmembers(object[, predicate])
Return all the members of an object in a list of
(name, value)
pairs sorted by nam
I don't think Python 2.6 has a __prepare__
method, so I can't swap out the default dict
for an ordered one. I can, however, replace it using a metaclass
and the __new__
method. Instead of inspecting line numbers, I think its easier and more efficient to just use a creation counter.
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = OrderedDict(
sorted(
[(name, attrs.pop(name)) for name, field in attrs.items() if isinstance(field, Field)],
key=lambda t: t[1].counter
)
)
return type.__new__(cls, name, bases, attrs)
class Form(object):
__metaclass__ = MetaForm
class Field(object):
counter = 0
def __init__(self):
self.counter = Field.counter
Field.counter += 1