【问题标题】:Python3 global dirPython3 全局目录
【发布时间】:2019-10-17 02:00:04
【问题描述】:

进入 python3.6 shell dir 时会产生以下结果:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

__builtins__ 产生所有内置的python 方法,例如those described here,而__name__ 将(总是?)是__main__。其他的呢:当(1)在python解释器中时,那些是否曾经填充过;或 (2) 运行脚本:如果是,什么时候?

这是一个运行名为temp.py的python脚本的示例:

if __name__ == '__main__':
    print (dir())
    print ("__annotations__: %s" % __annotations__)
    print ("__builtins__: %s" % __builtins__)
    print ("__cached__: %s" % __cached__)
    print ("__doc__: %s" % __doc__)
    print ("__file__: %s" % __file__)
    print ("__name__: %s" % __name__)
    print ("__package__: %s" % __package__)
    print ("__spec__: %s" % __spec__)

运行它:

$ python temp.py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
 __annotations__: {}
__builtins__: <module 'builtins' (built-in)> # <== always populated
__cached__: None
__doc__: None
__file__: temp.py # <== populated if running from a file/script
__name__: __main__ # <== populated (always with main?)
__package__: None

__annotation____cached____doc____package__ 是如何/何时填充的? __name__ 不是 __main__ 吗?

【问题讨论】:

  • 不清楚你在问什么。 “在全球蟒蛇级别填充”是什么意思?根据我提出的唯一解释,在您的测试中,所有其他人已经“填充在 global-python 级别”,或者 __builtins____name__ 还没有“在 global-python 级别填充"。
  • @user2357112 稍微更新一下问题。
  • 一些属性是在模块导入时设置的(参见docs.python.org/3/reference/import.html#loading)。仍然不清楚问题在问什么,您需要澄清“全局python级别”。
  • @wim 更新为在 python 解释器中说得更清楚。

标签: python python-internals


【解决方案1】:

__name__ 只是正在运行的脚本中的__main__。它包含访问它的模块的完全限定名称:

>>> __name__
'__main__'
>>> from logging import config
>>> config.__name__
'logging.config'

__cached____package__Import-related module attributes

__doc__ 保存当前模块或函数的文档字符串。

__annotations__ 持有 annotations 的全局变量。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-06-13
  • 2016-01-10
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
相关资源
最近更新 更多