Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a the attributes of a class, in the order they were defined? [duplicate]

Python comes with the handy dir() function that would list the content of a class for you. For example, for this class:

class C:
   i = 1
   a = 'b'

dir(C) would return

['__doc__', '__module__', 'a', 'i']

This is great, but notice how the order of 'a' and 'i' is now different then the order they were defined in.

How can I iterate over the attributes of C (potentially ignoring the built-in doc & module attributes) in the order they were defined? For the C class above, the would be 'i' then 'a'.

Addendum: - I'm working on some serialization/logging code in which I want to serialize attributes in the order they were defined so that the output would be similar to the code which created the class.

like image 290
Boaz Avatar asked Feb 17 '10 13:02

Boaz


1 Answers

I don't think this is possible in Python 2.x. When the class members are provided to the __new__ method they are given as a dictionary, so the order has already been lost at that point. Therefore even metaclasses can't help you here (unless there are additional features that I missed).

In Python 3 you can use the new __prepare__ special method to create an ordered dict (this is even given as an example in PEP 3115).

like image 123
nikow Avatar answered Sep 28 '22 01:09

nikow