Static type check for abstract method in Python

后端 未结 1 489
忘掉有多难
忘掉有多难 2021-02-14 21:05

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

1条回答
  •  醉梦人生
    2021-02-14 21:55

    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
    

    0 讨论(0)
提交回复
热议问题