Python3:为什么 __spec__ 有效?

Python3: Why does __spec__ work?

变量__spec__从何而来?

$ brew install python3
$ python3
Python 3.4.2 (default, Jan  5 2015, 11:57:21) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

# Under Python 2.7.x this gives a NameError
>>> None is __spec__
True

来自 the Python Language Reference, Part 5: The Import System(强调我的):

The __spec__ attribute must be set to the module spec that was used when importing the module. This is used primarily for introspection and during reloading. Setting __spec__ appropriately applies equally to modules initialized during interpreter startup. The one exception is __main__, where __spec__ is set to None in some cases.

New in version 3.4.

根据 Python 3 docs,如果您使用交互式提示,__spec__ 总是 None

When Python is started with the -m option, __spec__ is set to the module spec of the corresponding module or package. __spec__ is also populated when the __main__ module is loaded as part of executing a directory, zipfile or other sys.path entry.

In the remaining cases __main__.__spec__ is set to None, as the code used to populate the __main__ does not correspond directly with an importable module:

  • interactive prompt
  • -c switch
  • running from stdin
  • running directly from a source or bytecode file