The following code gives me a type mismatch error under strict typeschecking in Python.
class DataClass1(ABC):
@abstractmethod
def to_int(self) -> int:
return 1
class DataClass2(DataClass1):
def __init__(self, value: int):
self.value = value
def to_int(self) -> int:
return self.value
class WidgetClass(ABC):
@abstractmethod
def calculate(self, data: DataClass1) -> DataClass1:
pass
class WidgetClassImp(WidgetClass):
def calculate(self, data: DataClass2):
return data
The WidgetClassImp which receives a subclass of DataClass1 as argument causes the typemismatch to occur. This is surprising as DataClass2 is a subclass of DataClass1 and implements the DataClass1 interface.
Am I doing something wrong?
This can be solved by using annotation data: type[DataClass1].
The modified code will be as follows:
from typing import type
class DataClass1(ABC):
@abstractmethod
def to_int(self) -> int:
return 1
class DataClass2(DataClass1):
def __init__(self, value: int):
self.value = value
def to_int(self) -> int:
return self.value
class WidgetClass(ABC):
@abstractmethod
def calculate(self, data: DataClass1) -> DataClass1:
pass
class WidgetClassImp(WidgetClass):
def calculate(self, data: type[DataClass1]):
return data
The reason the above code works is that in the first case the type system assumes an instance of DataClass1. As DataClass2 is not an instance it raises a warning.
When we annotate it with type[DataClass1] it says to the typechecker to look for types of DataClass1. As DataClass2 is a subtype of DataClass1 no error will be raised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With