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 incorr
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