如何为基于服务类型返回对应配置类型的函数标注返回值?
类型注解方案:根据服务类获取对应配置类型
问题场景
现有代码定义了可继承的BaseConfig与泛型类BaseService,子类ConcreteService继承BaseService[ConcreteConfig]后,其get_config_type()方法能正确返回对应配置类型,mypy与IDE均可识别该类型。现在需要实现get_concrete_config()函数,仅传入服务类型即可返回对应配置类型,但返回类型注解存在两个问题:
- 若标注为
BaseConfig会丢失子类专属方法的类型信息 - 注解时无法直接引用传入服务参数的关联类型
原有代码示例:
from typing import TypeVar, Generic, Type class BaseConfig: pass class ConcreteConfig(BaseConfig): pass C = TypeVar("C", bound=BaseConfig) class BaseService(Generic[C]): CONF: Type[C] @classmethod def get_config_type(cls) -> Type[C]: return cls.CONF class ConcreteService(BaseService[ConcreteConfig]): CONF = ConcreteConfig conf = ConcreteService.get_config_type() reveal_type(conf) # Revealed type is "Type[mypy.ConcreteConfig]"
解决方案
重新定义绑定到泛型BaseService的TypeVar,通过关联关系提取服务类对应的配置类型参数,让类型检查器自动推导返回类型。
修改后的完整代码:
from typing import TypeVar, Generic, Type class BaseConfig: pass class ConcreteConfig(BaseConfig): pass C = TypeVar("C", bound=BaseConfig) class BaseService(Generic[C]): CONF: Type[C] @classmethod def get_config_type(cls) -> Type[C]: return cls.CONF class ConcreteService(BaseService[ConcreteConfig]): CONF = ConcreteConfig # 重新定义TypeVar,绑定到BaseService[C_co]并关联配置类型 C_co = TypeVar("C_co", bound=BaseConfig, covariant=True) T = TypeVar("T", bound=BaseService[C_co], covariant=True) def get_concrete_config(service: Type[T]) -> Type[C_co]: return service.get_config_type() # 测试类型推导 conf_type = get_concrete_config(ConcreteService) reveal_type(conf_type) # Revealed type is "Type[mypy.ConcreteConfig]"
方案说明
- 定义
C_co作为配置类型的协变TypeVar,确保子类配置可被正确向上兼容 - 将
T绑定到BaseService[C_co],让类型检查器关联服务类与对应配置类型 - 函数返回类型标注为
Type[C_co],mypy与IDE会根据传入的服务类自动推导具体配置类型,不会丢失子类专属方法的类型信息
内容的提问来源于stack exchange,提问作者Diddi Oskarsson
相关产品推荐
相关产品推荐

