Python 3.7:dir() 的新行为

Python 3.7: a new behaviour of dir()

我刚刚安装了 Python 3.7,在 inspect 模块中遇到了 dir() 的错误。请考虑这个最小示例。

1) 创建一个包含一行的模块 testdir

__dir__ = 'bla'

2) 在 python 中:

import testdir
dir(testdir)

导致 Python 3.7

出现这个错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

并在Python 3.6:

中正常运行
['__builtins__', '__cached__', '__dir__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

我知道 dir() 期望 __dir__ 是一个函数,但在 the docs 中这不是必须的,而是一个条件,并且文档在 [=33= 方面没有区别] 对比 3.7。为什么行为不同?是错误还是功能?

谢谢!

Python 3.7 现在也允许 __dir__ to be defined on modules。以前它只是被忽略了。条件部分是定义了if __dir__,它必须是可调用的,但不需要待定义.

相关 PEP (PEP 562) 实际包含规范:

The __dir__ function should accept no arguments, and return a list of strings that represents the names accessible on module:

def __dir__() -> List[str]: ...

If present, this function overrides the standard dir() search on a module.

不同之处在于模块中的 __dir__ 在 Python 3.7 之前被简单地忽略了。鉴于双下划线名称 必须 根据 Python 规范使用,因此没有必要在此处包含弃用(对于更改的行为),因为 __dir__ 作为字符串根本不符合规范。