Python中如何将返回类型指定为函数参数?
解决方案
要实现直接传递类型参数、支持类型检查和联合类型的配置取值函数,你可以结合TypeVar和Type做类型注解,同时处理联合类型的校验逻辑,具体实现如下:
代码实现
from typing import TypeVar, Type, Union from typing import TypeGuard # Python 3.10+ 可直接使用标准库的TypeGuard T = TypeVar('T') def is_instance(obj, type_: Union[type, tuple[type, ...]]) -> TypeGuard[T]: # 处理联合类型(包括int|None这种语法糖) if hasattr(type_, '__args__') and hasattr(type_, '__origin__') and type_.__origin__ is Union: return isinstance(obj, type_.__args__) # 处理多类型元组(比如(int, str)) elif isinstance(type_, tuple) and all(isinstance(t, type) for t in type_): return isinstance(obj, type_) # 处理单一类型 return isinstance(obj, type_) def get_from_cfg(key: str, t: Type[T]) -> T: # 模拟从配置文件获取值 val = 123 # 类型校验 if not is_instance(val, t): raise TypeError(f"值 {val} 不符合类型要求 {t}") return val
使用示例
# 单一类型 result_int = get_from_cfg('some_key', int) # 联合类型 result_opt_int = get_from_cfg('some_key', int | None) # 多类型联合 result_multi = get_from_cfg('some_key', str | int | bool)
核心说明
- 类型注解:用
Type[T]标注参数t,允许直接传入类型(如int、str)而非类型实例,解决了你之前需要传任意实例的问题;返回值-> T能让类型检查工具(如mypy、pyright)正确推断返回值类型。 - 联合类型处理:自定义
is_instance函数,通过识别Union类型的__args__属性,将联合类型拆解为类型元组,再用原生isinstance做校验,兼容int|None这类Python 3.10+的语法糖。
内容的提问来源于stack exchange,提问作者Lars Kiesow
相关产品推荐
相关产品推荐

