Search code examples
pythonlistclassvariables

How to get list of class variables in the order they are defined?


I have a class that specifies the column layout of a csv file as:

class RecordLayout(object):
    YEAR = 0
    DATE = 1
    MONTH = 2
    ID = 3
    AGE = 4
    SALARY = 5

I need to get the list of the class variables in the order they are defined.

So far, I tried:

[attr for attr in dir(RecordLayout()) if not callable(attr) and not attr.startswith("__")]

but it returns:

['AGE', 'DATE', 'ID', 'MONTH', 'SALARY', 'YEAR']

which is the class variables ordered alphabetically. I need the variables to be returned in the order they are defined in the class:

['YEAR', 'DATE', 'MONTH', 'ID', 'AGE', 'SALARY']

Is there a way to achieve this?


Solution

  • You should use an Enum for this.

    >>> class RecordLayout(Enum):
    ...     YEAR = 0
    ...     DATE = 1
    ...     MONTH = 2
    ...     ID = 3
    ...     AGE = 4
    ...     SALARY = 5
    ...
    >>> for i in RecordLayout:
    ...   print(i)
    ...
    RecordLayout.YEAR
    RecordLayout.DATE
    RecordLayout.MONTH
    RecordLayout.ID
    RecordLayout.AGE
    RecordLayout.SALARY