Search code examples
pythonmypypython-typing

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


I'm currently working on an API wrapper that will support asynchronous as well.
So I decided to create an asynchronous Client by inheriting from an asynchronous regular Client.

# Test

import requests
import aiohttp


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


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

Then, the mypy gave me the following error.
error: Return type "ClientResponse" of "request" incompatible with return type "Response" in supertype "Client"
I know I can use Union, but I don't want to import the async Client into the sync Client code, because I want the async Client to be an option that I can use if I do the following pip3 install myapiwrapper[async].
Is there any way I can resolve this error somehow?


Solution

  • I solved this question by using Generic.

    # Test
    
    from typing import TypeVar, Generic
    
    import requests
    import aiohttp
    
    
    ResponseT = TypeVar("ResponseT")
    
    
    class BaseClient(Generic[ResponseT]):
      def request(self, url: str) -> ResponseT:
        ...
    
    
    class Client(BaseClient[requests.Response]):
      def request(self, url: str) -> ResponseT:
        ...
    
    
    class AsyncClient(BaseClient[aiohttp.ClientResponse]):
      def request(self, url: str) -> ResponseT:
        ...