python - dir() 显示不存在的名称

标签 python python-2.7 python-3.x

我想检查Python中的pprint包。并调用dir()函数:

>>> import pprint
>>> [n for n in dir(pprint) if not n.startswith('_')]
['PrettyPrinter', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']
>>> pprint.__all__
['pprint', 'pformat', 'isreadable', 'isrecursive', 'saferepr', 'PrettyPrinter']

这比dir(pprint)pprint.__all__的不同更令人费解。 dir(pprint) 中还有一个附加的警告

我打开pprint.py的源码,发现没有名为warnings的函数。只有导入警告:

import sys as _sys
import warnings
__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
       "PrettyPrinter"]

最佳答案

这不应该让你感到困惑。 导入的名称在dir输出中可见,因为dir(module)列出了它的属性。 warnings 是模块 pprint 的一个属性,因为导入它会将其带入 pprint 模块命名空间(字典)中。

查看 dir's documentation tells you this :

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module’s attributes.

(强调我的)

module.__all__ 只是使用 import * 时导出的显式名称列表,它可以被视为给定模块的“公共(public) API”。

这两者有时可能相似,但更多时候它们是不同的。

关于python - dir() 显示不存在的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894384/

相关文章:

python - 使用 python-pandas 索引数据帧时无法获得非唯一标签的正确切片绑定(bind)

python - 如何将函数调用添加到列表?

python-3.x - 命令引发异常 : HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

python - 太空侵略者 : Loading Images

python - 查找两个 csv 文件中列名之间的差异?

Python 桌面应用程序

python - Ubuntu - 如何在 Python 3.3 而不是 Python 2.7 上安装 Python 模块 (BeautifulSoup)?

python .sort() 对 __lt__ 的优先级高于 __gt__?

python - 计算温度的偏导数(温度的水平平流)

python - 如何从字典中获取特定值?