Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hints for classes implementing an interface

Suppose I have an interface A with a single function.

class A(metaclass=ABCMeta):

    @abstractmethod
    def spam(self, x: int) -> str:
        pass

There are classes B and C that implement this interface, but they will not be directly initialized. I will have some factory method (say) that will return to me a suitable object implementing A. So in this case, when I implement spam in B and C, should I repeat the type hints? Practically, since B and C aren't directly used, the type hints for A seem sufficient. But I'm curious about the best practice in this situation; and if there are other issues to be considered.

like image 910
Jayanth Koushik Avatar asked Mar 22 '17 21:03

Jayanth Koushik


1 Answers

Presumably, since you implement B.spam, it won't be a trivial implementation (otherwise, why bother overriding A.spam?). So you probably should type check the body of B.spam. In that case, you need to provide type hints for the arguments and return values of B.spam; otherwise, mypy will treat those types as Any.

Note that if you do provide type hints, mypy will check that the type of B.spam is compatible with A.spam using its rules for subclassing, but only if B derives from A non-virtually; if you just A.register(B), mypy will ignore the inheritance relationship entirely. This is consistent with how the runtime will not look up .spam in the virtual base classes.

like image 199
max Avatar answered Oct 20 '22 23:10

max