Every module executes with its own set of global variables, which become the module's attributes. A module namespace is where a module's globals go; "executed in a fresh module namespace" means "executed with its own global variable environment".
A Python interpreter only executes a module's code the first time it's imported in any given program. Further import statements simply return the existing module object. This prevents exponential import explosion when modules a
and b
both import modules c
and d
, which both import e
and f
, etc. It also means that all modules see the same versions of, say, collections.defaultdict
, so type checks behave intuitively. runpy.run_module
says "run the code in this module, whether or not it was imported already, and don't count it as an import." If you run_module
a module and then __import__
it, the dict you got from run_module
will contain objects very similar to, but distinct from, the objects in the module you got from __import__
.