虽然变量current_timestamp
(因此也是函数返回值)和变量 time
是 datetime.datetime
类对象,以下代码引发 AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
from datetime import datetime
def current_time() -> datetime.datetime:
current_timestamp: datetime.datetime = datetime.now()
return current_timestamp
time: datetime.datetime = current_time()
print(time)
仅更改函数返回值的注释和 time
变量解决了问题。from datetime import datetime
def current_time() -> datetime:
current_timestamp: datetime.datetime = datetime.now()
return current_timestamp
time: datetime = current_time()
print(time)
谁能解释为什么注释datetime.datetime
只为函数返回值和 time
引发 AttributeError变量,但不适用于 current_timestamp
多变的?我正在运行 Python 3.8。
最佳答案
来自 PEP 526 , 这里定义了这个语法
Annotating a local variable will cause the interpreter to treat it as a local, even if it was never assigned to. Annotations for local variables will not be evaluated:
def f(): x: NonexistentName # No error.
However, if it is at a module or class level, then the type will be evaluated:
x: NonexistentName # Error! class X: var: NonexistentName # Error!
In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the
__annotations__
attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated annotations.
所以原因是注释是一种通用工具,留下了将它们用于类型签名以外的东西的可能性。在模块或类级别,您可以使用反射技术在运行时访问此信息,因此该值必须存在并且将被评估。然而,当应用于局部变量时,局部变量没有可用的反射,因此注释仅对解析代码的第三方工具有用,因此 Python 本身没有理由评估它。
值得注意的是
mypy
在第二个示例中将失败,如果您想使用实际的类型检查器,则必须在每个地方更正注释。
关于Python 变量和函数注释引发 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67048987/