Python 3.9中如何从TypeVar获取其绑定的目标类型?
实现方案
你可以直接读取TypeVar实例的__bound__属性获取绑定类型,再额外处理字符串形式的前向引用即可,Python 3.9 下可直接使用如下实现:
import sys from typing import TypeVar, Type # 你的原始定义 class Client: pass T = TypeVar('T', bound='Client') def get_bound_client_type(type_var: TypeVar) -> Type[Client]: bound_val = type_var.__bound__ # 处理前向引用的字符串场景 if isinstance(bound_val, str): # 从TypeVar定义所在的模块查找对应类 define_module = sys.modules[type_var.__module__] return getattr(define_module, bound_val) return bound_val # 测试调用 if __name__ == "__main__": client_cls = get_bound_client_type(T) print(client_cls) # 输出 <class '__main__.Client'> print(client_cls is Client) # 输出 True
注意事项
__bound__是TypeVar的内置属性,Python 3.9 到最新的 3.12 版本均支持该属性,可放心使用- 上述逻辑自动兼容
Client类和TypeVar定义在不同模块的场景,也兼容你使用字符串前向引用声明bound的写法 - 如果你不需要兼容未导入的前向引用场景,可以直接简化为
return type_var.__bound__即可
内容的提问来源于stack exchange,提问作者Fernando Lima
相关产品推荐
相关产品推荐

