1

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.

Community
  • 1
  • 1
pigeek
  • 67
  • 9

1 Answers1

0

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.

Community
  • 1
  • 1
orlp
  • 112,504
  • 36
  • 218
  • 315
  • @orip Thanks, [Mentioned solution](https://gist.github.com/DasIch/5562625) is exactly what I was looking for. – pigeek Apr 14 '15 at 02:42
  • @pigeek If my answer solved your problem, consider marking it as accepted by clicking the checkmark next to my answer. This helps future users, and gives both me and you a bit of reputation. Also, it's ORLP, not ORIP ;) – orlp Apr 14 '15 at 03:11