0

I have a list of declarations in a python file.

a = 1
b = 2
c = 3

which I import from another file, and try to iterate over it.

import themodule
for key, value in themodule.__dict__.items():
   if not key.startswith('_'):
       ...

However, it is critical that I get the declarations in the order they are written. Is there any way to guarantee this?

pault
  • 41,343
  • 15
  • 107
  • 149
blue_note
  • 27,712
  • 9
  • 72
  • 90
  • What version of python? – pault Jun 28 '19 at 14:27
  • @pault: version 3.6 – blue_note Jun 28 '19 at 14:28
  • https://pymotw.com/2/collections/ordereddict.html - take a look at this – alexanderhurst Jun 28 '19 at 14:29
  • 3
    Then you should be good: [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744). *As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted* – pault Jun 28 '19 at 14:29
  • @alexanderhurst: I can't use that if the automatically imported __dict__ is not already in random order. – blue_note Jun 28 '19 at 14:30
  • 1
    Possible duplicate of [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – pault Jun 28 '19 at 14:30
  • 1
    Related: https://stackoverflow.com/questions/54521087/retrieving-available-functions-in-script-same-order – Ry- Jun 28 '19 at 14:32
  • 6
    "It's critical that I get the declarations in the order they are written." Why? What is your use case? – chepner Jun 28 '19 at 14:33
  • @chepner: matching patterns in order of preference. – blue_note Jun 28 '19 at 14:35
  • 1
    @blue_note Then use a *list*, which is guaranteed to be ordered. – chepner Jun 28 '19 at 14:43
  • dictionaries maintain *insertion* order. with that in mind, it seems you could answer this by trial & error. a quick test against a Class.__dict__ suggests the answer is "Yes". – David Zemens Jun 28 '19 at 14:46
  • It truly makes no sense. `dict` just doesn't promise to be ordered. You should never rely on implementation details. As it can be changed at any time. Even worse, switching to other implementation(For example, changing to pypy for better server performance) can lead to a silent fail which you may never figure out why. Do your self a favor and use `OrderedDict`. – Sraw Jun 28 '19 at 15:05
  • 2
    OP is essentially asking *how* `__dict__` is implemented with regards to insertion order -- specifically, are the items added to `__dict__` in the order in which they appear in the module? Or are they inserted by some other logic? If it is not "ordered", then casting that return to an `OrderedDict` still doesn't solve the problem, which is "How can I ensure that I iterate over the members by order of appearance?" – David Zemens Jun 28 '19 at 17:21
  • @Sraw: `dict` is ordered as of Python 3.7. It was an implementation detail in 3.6. – Ry- Jun 28 '19 at 18:55

0 Answers0