Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static type check for abstract method in Python

Tags:

python

pycharm

How do I make sure that a method implementing an abstract method adheres to the python static type checks. Is there a way in pycharm to get an error if the return type is incorrect for the implemented method?

class Dog:
    @abc.abstractmethod
    def bark(self) -> str:
        raise NotImplementedError("A dog must bark")

class Chihuahua(Dog):
    def bark(self):
        return 123

So for the above code I would want to get some sort of a hint that there is something wrong with my chihuahua

like image 823
Ryan Avatar asked Jan 08 '19 08:01

Ryan


1 Answers

No there's not a (simple) way to enforce this.

And actually there isn't anything wrong with your Chihuahua as Python's duck typing allows you to override the signature (both arguments and types) of bark. So Chihuahua.bark returning an int is completely valid code (although not necessarily good practice as it violates the LSP). Using the abc module doesn't change this at all as it doesn't enforce method signatures.

To "enforce" the type simply carry across the type hint to the new method, which makes it explicit. It also results in PyCharm showing a warning.

import abc

class Dog:
    @abc.abstractmethod
    def bark(self) -> str:
        raise NotImplementedError("A dog must bark")

class Chihuahua(Dog):
    def bark(self) -> str:
        # PyCharm warns against the return type
        return 123
like image 195
101 Avatar answered Nov 18 '22 09:11

101