如何为接受类型/类型提示并返回对应类型对象的函数添加类型提示?
为支持类型提示参数的函数添加正确的类型注解
问题描述
我有一个函数,接受类型(或类型提示)作为参数,返回匹配该类型的对象。示例代码如下:
def get_object_of_type(typ): ... x = get_object_of_type(int) # x被保证为int类型 y = get_object_of_type(str | bytes) # y被保证为字符串或bytes对象
尝试用Python 3.12泛型语法添加类型提示,但该方案仅对普通类型有效,无法处理str | bytes这类联合类型:
def get_object_of_type[T](typ: type[T]) -> T: ...
请问如何修改类型提示,让静态分析工具能识别函数的行为?
解决方案
方案一:简洁通用版
要让函数同时适配普通类型和联合/泛型类型提示,可使用TypeVar绑定返回类型,参数类型设为object(覆盖所有合法的类型提示对象)。静态分析工具会根据传入的参数自动推导返回类型:
from typing import TypeVar, cast T = TypeVar('T') def get_object_of_type(typ: object) -> T: # 函数实现示例 if typ is int: return cast(T, 42) elif typ is str: return cast(T, "hello") elif isinstance(typ, UnionType): # 处理联合类型,示例返回第一个类型的实例 return cast(T, typ.__args__[0]()) # 其他类型的处理逻辑 ...
方案二:精确重载版
如果需要更严谨的参数类型校验,可结合typing.overload为不同类型的参数提供专属签名,覆盖普通类型、联合类型、泛型类型等场景:
from typing import overload, TypeVar, Type, UnionType, GenericAlias T = TypeVar('T') @overload def get_object_of_type(typ: Type[T]) -> T: ... @overload def get_object_of_type(typ: UnionType) -> T: ... @overload def get_object_of_type(typ: GenericAlias) -> T: ... def get_object_of_type(typ): # 统一实现逻辑 ...
两种方案都能让静态分析工具准确识别:传入int时返回int,传入str | bytes时返回str | bytes,传入list[int]时返回list[int]。
内容的提问来源于stack exchange,提问作者J E K
相关产品推荐
相关产品推荐

