-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Description
Bug Report
Mypy reports type errors but Pylance successfully provides autocompletion for the following code sample.
To Reproduce
from typing import Generic, Optional, Type, TypeVar
class Car:
...
class FastCar(Car):
def go_fast(self) -> None:
...
class SlowCar(Car):
def go_slow(self) -> None:
...
T = TypeVar("T", bound=Car)
class Driver(Generic[T]):
def __init__(self, car_type: Type[T] = FastCar):
self.car = car_type()
driver1 = Driver()
driver1.car.go_fast()
driver2 = Driver(car_type=SlowCar)
driver2.car.go_slow()
I have a library with a base class Car
and several sub-classes for different kinds of cars. A Driver
gets assigned their type of car during instance creation. A certain car type is used as the default. VS code correctly provides autocompletion for the car attribute of each driver, without requiring the user to specify the car type twice, like driver1 = Driver[SlowCar](car_type=SlowCar)
. However, Mypy is not happy.
Actual Behavior
tmp.py:22: error: Incompatible default for argument "car_type" (default has type "Type[FastCar]", argument has type "Type[T]") [assignment]
tmp.py:27: error: Need type annotation for "driver1" [var-annotated]
Found 2 errors in 1 file (checked 1 source file)
I can not make sense of the first error because T
is bound to Car
and FastCar
is a sub-class of Car
. What should I use here instead?
Mypy should consider the default argument to the __init__
method and not show the second error. Either adding the car type explicitly (driver1 = Driver(car_type=FastCar)
) or adding the car type in brackets (driver1 = Driver[FastCar]()
) solves the second error but I don't want to put that burden on the user.
I could add a # type: ignore
to the __init__
method and remove the default car type. That would give users autocompletion in VS code and silence Mypy but that doesn't feel clean. Am I misusing the generic annotation by passing it as an argument instead of providing it in brackets?
Your Environment
- Mypy version used: 1.2.0
- Python version used: 3.9