dir()显示不存在的名称

时间:2017-03-20 01:14:57

标签: 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__的不同。 warnings中还有dir(pprint)pprint.py

我打开warnings的来源,发现没有名为import warnings的函数。只有import sys as _sys import warnings __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", "PrettyPrinter"]

type Circle = { kind: "circle" }
type Rectangle = { kind: "rectangle" }
type Triangle = { kind: "triangle" }
type Shape = Circle | Rectangle | Triangle

function numberOfSides(shape: Shape) {
    switch (shape.kind) {
        case "circle": return 0;
    }
}

2 个答案:

答案 0 :(得分:3)

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

查看dir's documentation tells you this

  

默认dir()机制对不同类型的对象的行为有所不同,因为它试图产生最相关的信息,而不是完整的信息:

     
      
  • 如果对象是模块对象,则列表包含模块属性的名称
  •   

(强调我的)

module.__all__只是在使用import *时导出的名称的明确列表,可以将其视为"公共API"一个给定的模块。

这两者有时可能相似,但往往不同。

答案 1 :(得分:1)

dir()__all__的结果自然不同 - 它们提供不同的功能。

如果您致电help(dir),则会收到:

Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

您正在模块上调用dir,因此它返回模块的属性。这些属性是模块中可用的任何属性(包括它导入的warnings模块。)

另一方面,程序包/设计者设置__all__来指示从模块导入所有内容时默认导入的内容(即from module import *)。

相关问题