如何为返回抽象类实现结果类型的方法正确添加类型提示
问题描述
我在为方法的返回结果添加类型提示时遇到了问题。该方法向服务器发送操作,收到响应后返回解析后的操作结果。每个ServerOperation都有专属的结果类型,我需要获取该类型。
当前代码:
def send(self, operation: ServerOperation): # 此处应如何声明返回类型? command = operation.get_command(self.__request_executor.conventions) self.__request_executor.execute_command(command) if isinstance(operation, ServerOperation): return command.result
相关类定义:
ServerOperation类
class ServerOperation(Generic[T]): @abstractmethod def get_command(self, conventions: "DocumentConventions") -> RavenCommand[T]: raise NotImplementedError()
RavenCommand类(简化版)
class RavenCommand(Generic[ResultClass]): def __init__(self, result_class: Type[ResultClass] = None): self._result_class = result_class self.result: Union[None, ResultClass] = None
实现示例:
class GetClientConfigurationOperation(MaintenanceOperation): def get_command(self, conventions: "DocumentConventions") -> "RavenCommand[GetClientConfigurationOperation.Result]": return self.GetClientConfigurationCommand() class GetClientConfigurationCommand(RavenCommand): def __init__(self): super().__init__(GetClientConfigurationOperation.Result) def is_read_request(self) -> bool: return False def create_request(self, node: ServerNode) -> requests.Request: return requests.Request(method="GET", url=f"{node.url}/databases/{node.database}/configuration/client") def set_response(self, response: str, from_cache: bool) -> None: if response is None: return self.result = GetClientConfigurationOperation.Result.from_json(json.loads(response)) class Result: def __init__(self, etag: int, configuration: ClientConfiguration): self.etag = etag self.configuration = configuration @staticmethod def from_json(json_dict: dict) -> GetClientConfigurationOperation.Result: return GetClientConfigurationOperation.Result( json_dict["Etag"], ClientConfiguration.from_json(json_dict["Configuration"]) )
解决方案
要正确为send方法添加返回类型提示,只需利用ServerOperation的泛型参数绑定结果类型,具体步骤如下:
为
send方法引入泛型参数
定义一个类型变量T,将operation参数的类型指定为ServerOperation[T],这样类型检查器就能关联操作对应的结果类型。指定返回类型为
Optional[T]
由于RavenCommand.result的类型是Union[None, ResultClass],对应到ServerOperation的泛型T,返回类型应声明为Optional[T](需提前从typing导入Optional和TypeVar)。
修改后的send方法代码:
from typing import TypeVar, Optional T = TypeVar("T") def send(self, operation: ServerOperation[T]) -> Optional[T]: command = operation.get_command(self.__request_executor.conventions) self.__request_executor.execute_command(command) return command.result
关键说明
- 原代码中
isinstance(operation, ServerOperation)的判断是冗余的,因为参数类型已经限定为ServerOperation[T],可以直接移除。 - 通过泛型绑定,类型检查器能自动推断出
command是RavenCommand[T]类型,因此command.result的类型与返回类型Optional[T]完全匹配。
内容的提问来源于stack exchange,提问作者poisson
相关产品推荐
相关产品推荐

