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
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With