1

Given these two classes:

class MyClass(ABC):
    @abstractmethod
    def my_method(self, my_parameter: str):
        pass
    
class MySecondClass(MyClass):
    def my_method(self, my_parameter): 
        pass

Does my_parameter in my_method of MySecondClass have an inferred type of Any or str based on PEP 484? I couldn't find an example detailing the above within the linked document.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52

1 Answers1

2

It's Any. You can try it out by running mypy:

from abc import ABC, abstractmethod

class MyClass(ABC):
    @abstractmethod
    def my_method(self, my_parameter: str):
        pass
    
class MySecondClass(MyClass):
    def my_method(self, my_parameter):
        reveal_type(my_parameter)
        pass

MySecondClass().my_method(3)

With or without the --check-untyped-defs flag, this passes type checking, and reveal_type reports Any as the type. (Without the flag, type checking is also skipped for the method body.)


Note that even with annotations, it is permitted for an overriding method to have a different signature than an overridden method, as long as the overriding method's signature is more permissive. For example, a method that takes an Animal can override a method that takes a Dog.

user2357112
  • 260,549
  • 28
  • 431
  • 505