I think I finally figured out they need to use this DeclarativeFieldsMetaclass (to turn the class fields into instance variables and maintain their order with an ordered/sorted dict). However, I’m still not quite sure why they opted to use a BaseForm rather than implementing everything directly within the Form class?
They left a comment,
class Form(BaseForm):
"A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one
# to define a form using declarative syntax.
# BaseForm itself has no way of designating self.fields.
But I don’t really understand it. “In order to abstract the way self.fields is specified” — but Python calls DeclarativeFieldsMetaclass.__new__ before Form.__init__, so they could have taken full advantage of self.fields inside Form.__init__ as is; why do they need an extra layer of abstraction?
Source:
Output:
Looks like
MetaForm.__new__is called twice. Once forFormand once forCustomForm, but never forBaseForm. By having a clean (empty)Formclass, there won’t be any extraneous attributes to loop over. It also means that you can defineFieldsinside theBaseFormthat could be used for internal use, but avoid rendering.