metaclass - How to get attributes in the order they are declared in a Python class? -
as described in pep435, enum can defined way:
class color(enum): red = 1 green = 2 blue = 3 and resulting enum members of color can iterated in definition order: color.red, color.green, color.blue.
this reminds me of form in django, in fields can rendered in order declared in form subclass. implemented maintaining field counter, every time new field instantiated counter value incremented.
but in definition of color, don't have formfield, how can implement this?
in python 3, can customize namespace class declared in metaclass. example, can use ordereddict:
from collections import ordereddict class enummeta(type): def __new__(mcls, cls, bases, d): print(d) return type.__new__(mcls, cls, bases, d) @classmethod def __prepare__(mcls, cls, bases): return ordereddict() class color(metaclass=enummeta): red = 1 green = 2 blue = 3 this prints
ordereddict([('__module__', '__main__'), ('red', 1), ('green', 2), ('blue', 3)])
Comments
Post a Comment