我想检查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/