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

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -