It's documented that the definition order in classes is preserved (see also PEP 520):
If the metaclass has no
__prepare__
attribute, then the class namespace is initialised as an empty ordered mapping.
Is the definition order also preserved in module objects?
# foo_bar.py
def foo():
pass
def bar():
pass
I've experimented with the module above (also swapping the ordering), and it did seem to be reliable:
>>> import foo_bar
>>> for name in foo_bar.__dict__:
... if not name.startswith('_'):
... print(name)
...
foo
bar
Presumably, the module namespace also uses a compact dict underneath, or perhaps it follows from the fact that the type(foo_bar)
is a <class 'module'>
that it must also respect definition order, like any other class. However, I'm not sure if this is a feature guaranteed by Python, or just a CPython implementation detail. Are the names in modules required to respect definition ordering?