Python 变量和函数注释引发 AttributeError

标签 python python-3.x

虽然变量current_timestamp (因此也是函数返回值)和变量 timedatetime.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/

相关文章:

python - 模拟 Flask 的 `send_from_directory` 用于测试

python - 最大子图

python - 全局语句的范围

python - 我试图在Python中运行一些代码,并得到错误“元组索引超出范围”。有人知道我在想什么吗?

python - Pytest 适用于旧模拟,但不适用于 unittest.mock

python - 为什么我必须为每个新项目重新安装所有 python 模块? (皮查姆)

python - Django:请求页面时异步加载数据?

python - 项目分配 Tensorflow 2.0 - TypeError : 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment

python - 在多索引数据框中创建不存在的列

python-3.x - 尽管之前的实现工作正常,但可整除计算器仍失败