Search code examples
pythonpython-2.7ordereddictionary

Reading class attributes in the same order as declared in Python


I am developing some code that requires access to attributes of a class in the same order that they were declared. I have found the following answer to a similar question: https://stackoverflow.com/a/4460034 however as it was mentioned in the comment, it is not threads safe. I am using Python 2.7. I am wondering if there is a way to force python using OrderedDict when collecting attributes?

The actual use case is to have an ability to define Structs like it is done here (http://code.activestate.com/recipes/498149/), but the solution should be thread safe.


Solution

  • Your exact problem has a solution in Python3 using a metaclass. It's described in the docs.

    However, it uses the __prepare__ classmethod, which is not available in Python2.7. After some googling I did find this solution that ports __prepare__ to Python2.7, but it's incredibly hacky and dirty.

    To me it sounds like you're having the XY problem, and your problem can be solved through a different approach.