You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python变量中查询其声明的类型注解?

查询已赋值变量的类型注解问题

问题场景

在Python中定义带有类型注解的变量:

web: websockets.WebSocketClientProtocol = None

随后将其赋值为websockets.connect("wss://some_website")的返回结果,此时执行type(web)得到的实际类型为<class 'websockets.legacy.client.Connect'>。

尝试使用get_type_hints(web)获取类型注解时触发报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.8/typing.py", line 1255, in get_type_hints
    raise TypeError('{!r} is not a module, class, method, '
TypeError: <websockets.legacy.client.Connect object at 0x7fb732408760> is not a module, class, method, or function.

同时调用get_type_hints(websockets.connect)返回空字典。需要解决的问题是:若事先不知道变量web的类型注解为websockets.WebSocketClientProtocol,如何查询到该变量的类型注解?

解决方案

直接访问当前作用域的__annotations__字典,通过变量名即可获取对应的类型注解。示例代码如下:

>>> import websockets
>>> from typing import get_type_hints
>>> web: websockets.WebSocketClientProtocol = None
>>> web = websockets.connect("wss://some_website")
>>> from __future__ import annotations    # 此行非必需
>>> __annotations__['web']
<class 'websockets.legacy.client.WebSocketClientProtocol'>

内容的提问来源于stack exchange,提问作者q0987

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 20:15:43