Python 变量注解 x: int 实际执行了什么?
数据小陈
结论
x: int 是变量注解语句,并不赋值。它不会创建名为 x 的变量,也不会给 x 绑定任何值。所以执行 x: int 后再读取 x,得到 NameError 很正常。注解主要用于静态类型检查、文档和工具读取;Python 解释器在运行时不会因为注解去检查或强制类型。
解释器实际执行了什么
在模块或类作用域里,普通注解语句会求值注解表达式,再把它记录到当前模块或类的 __annotations__ 字典中,但不会把目标名字绑定到值。例如:
>>> x: int
>>> __annotations__
{'x': <class 'int'>}
>>> 'x' in globals()
False
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
int 被求值并存入 __annotations__['x'],但 x 本身没有出现在全局命名空间里。注解表达式如果有副作用,也会在这一步执行:
>>> y: print("annotation evaluated")
annotation evaluated
>>> __annotations__['y'] is None
True
如果注解表达式里的名字不存在,并且模块顶层没有启用延迟注解,那么执行到该行时通常会抛出 NameError:
>>> z: NotDefined
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'NotDefined' is not defined
不同作用域下的行为
- 模块作用域:
x: int会把int记录到模块的__annotations__,但不会创建全局变量x。 - 类作用域:
class C: x: int会把注解记录到C.__annotations__,但不会创建类属性x。比如hasattr(C, 'x')仍然是False。 - 函数作用域:函数内部的局部变量注解不会求值,也不会保存到
__annotations__,同样不会绑定值。要用到实际值时,还是得赋值。
类作用域示例:
>>> class C:
... x: int
...
>>> C.__annotations__
{'x': <class 'int'>}
>>> hasattr(C, 'x')
False
怎样让变量可用
如果希望 x 可用,就必须进行绑定,例如赋值:
x: int = 0
print(x) # 0
或者只赋值:
x = 0
运行时不会检查 x: int 和实际赋值的类型是否一致:
>>> x: int
>>> x = "not an int"
>>> x
'not an int'
>>> __annotations__['x']
<class 'int'>
注意事项
- 注解不是声明;Python 变量在绑定时才出现。
from __future__ import annotations会改变注解的求值时机和存储形式,具体行为要看所用的 Python 版本;需要解析时可以用typing.get_type_hints()。- 类型检查由 mypy、pyright 等静态工具完成,解释器不会在运行时自动检查。
- 如果只想写类型提示,可以写
x: int;如果要读取变量,就必须给它赋值。
备注:内容仅供参考。
