I have the following code:
from typing import Callable
MyCallable = Callable[[object], int]
MyCallableSubclass = Call
As I was writing this question, I realized the answer to my problem, so I figured I'd still ask the question and answer it to save people some time with similar questions later.
What's going on?
Notice that last example from the Mypy docs:
Callable
is an example of type that behaves contravariant in types of arguments, namelyCallable[[Employee], int]
is a subtype ofCallable[[Manager], int]
.
Here, Manager
subclasses from Employee
. That is, if something is expecting a function that can take in managers, it's alright if the function it gets overgeneralizes and can take in any employee, because it will definitely take in managers.
However, in our case, MyObject
subclasses from object
. So, if something is expecting a function that can take in objects, then it's not okay if the function it gets overspecifies and can only take in MyObject
s.
Why? Imagine a class called NotMyObject
that inherits from object
, but doesn't inherit from MyObject
. If a function should be able to take any object, it should be able to take in both NotMyObject
s and MyObject
s. However, the specific function can only take in MyObject
s, so it won't work for this case.
How can I fix it?
Mypy is correct. You need to have the more specific function (MyCallableSubclass
) as the type, otherwise either your code could have bugs, or you are typing incorrectly.