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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With