In python < 3.6, fields order is not preserved in generated init
smarie opened this issue · 1 comments
smarie commented
We should probably use a creation_counter
on fields like django did:
smarie commented
Note to future self: this can be solved using metaclasses in python 3.x < 3.6 but not in python 2 since the __prepare__
method did not exist at the time;
class OrderTrackingMeta(type):
"""
Metaclass to track the order of class members.
The problem with this is that it is not compliant with python 2.
"""
# The prepare function
@classmethod
def __prepare__(metacls, name, bases): # No keywords in this case
return OrderedDict()
# The metaclass invocation
def __new__(cls, name, bases, classdict):
new_type = type.__new__(cls, name, bases, classdict)
new_type.__ordered_dict__ = classdict
return new_type
See https://www.python.org/dev/peps/pep-3115/#example and https://stackoverflow.com/a/27113652/7262247