繁体   English   中英

如何通过不使用 Union 来修复 mypy 与返回类型不兼容的错误

[英]How to fix mypy's incompatible with return type error by not using Union

我目前正在开发一个 API 包装器,它也将支持异步。
所以我决定通过从异步常规客户端继承来创建一个异步客户端。

# Test

import requests
import aiohttp


class Client:
  def request(self, url: str) -> requests.Response:
    ...


class AsyncClient(Client):
  def request(self, url: str) -> aiohttp.ClientResponse:
    ...

然后,mypy 给了我以下错误。
error: Return type "ClientResponse" of "request" incompatible with return type "Response" in supertype "Client"
我知道我可以使用Union ,但我不想将异步客户端import同步客户端代码,因为我希望异步客户端成为我可以使用的选项,如果我执行以下pip3 install myapiwrapper[async]
有什么办法可以解决这个错误吗?

我通过使用Any解决了这个问题。

# Test

from typing import Any

import requests
import aiohttp


class BaseClient:
  def request(self, url: str) -> Any:
    ...


class Client(BaseClient):
  def request(self, url: str) -> requests.Response:
    ...


class AsyncClient(BaseClient):
  def request(self, url: str) -> aiohttp.ClientResponse:
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM