Boaz Boaz - 4 years ago 149
Python Question

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

Python comes with the handy

function that would list the content of a class for you. For example, for this class:

class C:
i = 1
a = 'b'

would return

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

This is great, but notice how the order of
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'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.

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download