How to get Class attributes order

Before python 3.6 it was difficult to get attributes order from a class.

Let’s say, for instance, you want to create a listing class which contains columns to display :

With python 2.7 you will get :

With python 3.5 you will get :

And finally, with python 3.6, there is no problem any more : attributes key are already sorted : you will get :

Obviously, if you want to display column in the same order as they have been declared, you got a problem before python 3.6.

Fortunately, there are some solutions. For python 2.x, the idea is to add a counter in Column class, then to order column attributes following this counter :

You will get :


The only drawback is that you will get attribute order only for one base class, here Column class.

With python3, you can now choose where will be stored members by defining __prepare__ method, for python < 3.6 choose an OrderedDict :

You will get:

With this method, you will get all class members,  not only some attributes having a specific base class.


Et voilà.