0

http://docs.python.org/2/library/runpy.html#runpy.run_module

My question is about this part of the run_module documentation.

... and then executed in a fresh module namespace.

What is a "module namespace" in python? In what ways does runpy differ from import?

4

1 回答 1

1

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__.

于 2013-07-24T17:42:46.257 回答