Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch when using subclasses

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?

like image 320
Kurian Kattukaren Avatar asked Sep 17 '26 21:09

Kurian Kattukaren


1 Answers

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.

like image 73
Kurian Kattukaren Avatar answered Sep 19 '26 09:09

Kurian Kattukaren