No, the order of attributes is normally not guaranteed, as Python stores attributes in a dictionary.
Instead, wtforms
uses special tricks to detect in what order fields were defined, that work around this. Every time you create a Field
object, a counter is incremented and a unique number is assigned to the field instance. This makes the objects orderable:
class UnboundField(object):
_formfield = True
creation_counter = 0
def __init__(self, field_class, *args, **kwargs):
UnboundField.creation_counter += 1
# [...]
self.creation_counter = UnboundField.creation_counter
So the Field
instances have a creation_counter
value that is incremented each time a new field is added to a form.
The FormMeta
class then uses that value on the fields to sort them in the correct order:
fields.sort(key=lambda x: (x[1].creation_counter, x[0]))