Is there a definition order in the module namespace?

It states that the order of definition in the classes is preserved (see also PEP 520 ):

If the metaclass does not have the __prepare__ attribute, then the class namespace is initialized as empty ordered mappings.

Is the definition order also stored in module objects?

 # foo_bar.py def foo(): pass def bar(): pass 

I experimented with the above module (also changing the order) and it seemed 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 at the bottom, or perhaps it follows from the fact that type(foo_bar) is <class 'module'> , that it must also follow the definition order like any other class. However, I'm not sure if this is a function guaranteed by Python, or just a detail of the implementation of CPython. Are names in modules mandatory for determining the order of definition?

+7
python python-module
source share
1 answer

Built-in classes, such as the module class, do not go through the usual mechanism of user-defined do * classes and, as such, do not use metaclass.__prepare__ , PEP 520 does not apply to them, so the guarantees that it can distribute cannot be applied here.

Currently, the ordering of the module namespace is preserved due to the fact that the dictionary ordered by order, like the dictionary itself, is considered as an implementation detail.


* User classes first go through build_class (the LOAD_BUILD_CLASS function of the bytecode is loaded when you dis the class statement) in bltinmodule.c . This is the only place where __prepare__ is called (which returns a PyDict_New from type_prepare if a custom meta with __prepare__ not defined).

+1
source share

All Articles