Return subclass when return type is TypeVar

Viewed 80

I have the following file t.py:

from typing import overload, TypeVar, List, Any, Iterable

class Animal: ...
class Dog(Animal): ...

T = TypeVar('T', bound=Animal)

def foo(self: T) -> T:
    return self

, which type checks fine:

$ mypy t.py 
Success: no issues found in 1 source file
(venv) marco@marco-Predator-PH315-52:~/tmp$

However, if I change it to:

from typing import overload, TypeVar, List, Any, Iterable

class Animal: ...
class Dog(Animal): ...

T = TypeVar('T', bound=Animal)

def foo(self: T) -> T:
    if isinstance(self, Dog):
        return self
    else:
        return self

then I get a typing error:

$ mypy t.py 
t.py:10: error: Incompatible return value type (got "Dog", expected "T")
Found 1 error in 1 file (checked 1 source file)

Why is that, and how can I make it type check fine if I have an if isinstance(self, Dog) block?

0 Answers
Related