Python3:为什么__spec__有效?

时间:2015-01-06 06:18:47

标签: python python-3.x

变量__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

2 个答案:

答案 0 :(得分:6)

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

  

__spec__属性必须设置为导入模块时使用的模块规范。这主要用于内省和重新加载。设置__spec__适用于modules initialized during interpreter startup一个例外是__main__,其中__spec__在某些情况下设置为无

     

版本3.4中的新功能。

答案 1 :(得分:2)

根据Python 3 docs,如果您使用交互式promt,__spec__始终为None

  

使用-m选项启动Python时,__spec__设置为   相应模块或包的模块规格。 __spec__也是   在__main__模块作为执行a的一部分加载时填充   目录,zipfile或其他sys.path条目。

     

在其余情况下,__main__.__spec__ 设置为无,作为代码   用于填充__main__并不直接对应于   可导入的模块:

     
      
  • 互动提示
  •   
  • -c switch
  •   
  • 从stdin
  • 运行   
  • 直接从源或字节码文件运行
  •