0

I'd like to make my python IDE give me an error or warning when I implement derived classes that break the base class contract and return the wrong type.

( By the way this is not a theoretical interest question, this kind of mistake actually happened and bit me at run time )

class Hair(ABC):
    @abstractmethod
    def show(self):
        pass

class DogHair(Hair):
    def show(self):
        print("|||||")

class Student: # a completely unrelated class used by mistake
    def print_student_details(self):
        print("Some student info...")

class Animal(ABC):
    @abstractmethod
    def get_hair(self) -> Hair:
        pass

class Dog(Animal):
    def get_hair(self) -> Student: # OOPS! does not conform to the base class contract!
        return Student()

dog:Dog = Dog()
dog.get_hair().print_student_details() # logical mistake, but works

is there any way to get an error or at least a warning for this?

I am using python 3.8, VS Code and pycharm

Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • 2
    A static type checker *should* warn about this. Python itself won't, ever. – deceze Nov 02 '21 at 09:39
  • well, if I remove the hint about returning `Student`, then it shows a "warning" that `Hair` doesn't have the attribute, you are possibly simply overriding the parent type hint – Matiiss Nov 02 '21 at 09:47

0 Answers0