Reputation: 730
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?
Upvotes: 1
Views: 270
Reputation: 562
Old question but top google search result, so here's my answer after some more research.
Use RecordLayout().__dir__()
and filter out the entries which are not needed. __dir__()
should provide the entries in the order they were defined, whereas dir()
applies a sort.
How did I get here?
Starting with "PEP 520 -- Preserving Class Attribute Definition Order" and then ended up at this discussion thread https://mail.python.org/pipermail/python-dev/2016-September/146382.html
>>> class Example:
... def __dir__(self):
... return "first second third fourth".split()
...
>>> dir(Example())
['first', 'fourth', 'second', 'third']
>>> Example().__dir__()
['first', 'second', 'third', 'fourth']
Upvotes: 0
Reputation: 599580
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
Upvotes: 3