Recently I came across this problem where I had to list all the members of a class in the order in which they were declared. Normally, to list all the members of the class, one would use dir to get all the attributes of the object. Following example demonstrates the working of dir command:
We can see that the class members are not listed in the order in which they are declared. I started googling for the answers and found a solution here. Sample output with this solution is:
To understand how this works, we first have to understand what a metaclass is. Metaclasses are basically classes that are used to create classes. In python, class is an object and it is basically an instance of a metaclass called type. Let’s look at some code:
So, what we did while using OrderedClassMembers was that we defined our own metaclass. We use the magic method called __prepare__ to achieve our goal. When we declare a class in python, a namespace for that particular class in prepared using a dict object. However dict fails to preserve order of the keys for the namespace. However, using __prepare__ method which was introduced in Python 3 (check PEP3115) we can define the structure that is used to create this namespace. Now when __new__ runs, we get an OrderedDict instead of a normal dict. In this dictionary, we add another key called __ordered__ which can than be used to get the desired result.