Static Type Check For Abstract Method In Python
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
Solution 1:
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
classDog:@abc.abstractmethod
defbark(self) -> str:
raise NotImplementedError("A dog must bark")
classChihuahua(Dog):defbark(self) -> str:# PyCharm warns against the return typereturn123
Post a Comment for "Static Type Check For Abstract Method In Python"