views:

111

answers:

2

Hi all,

Pyhon 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'.

Thanks, Boaz

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.

+1  A: 

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

nikow
A: 

This information is not accessible, since attributes are stored in a dict, which is inherently unordered. Python does not store this information about order anywhere.

If you want your serialization format to store things in a certain order you would specify that order explicitly. You would not use dir, which contains things you don't know or care about, you would explicitly provide a list (or whatever) describing what to serialize.

Mike Graham