0
from typing import Callable

class SuperClass:
    pass

class SubClass(SuperClass):
    pass


def a_function(another_function: Callable[[SuperClass], None]):
    pass

def superclass_callable(temp: SuperClass) -> None:
    pass

def subclass_callable(temp: SubClass) -> None:
    pass


a_function(superclass_callable)
a_function(subclass_callable)

superclass_callable(SuperClass())
superclass_callable(SubClass())

In the code above, PyCharm is highlighting a_function(subclass_callable) and telling me Expected type '(SuperClass) -> None, got '(temp: SubClass) -> None' instead. Everything I've seen in my searches says that the type hinting should accept subclasses, so I can't figure out what's going wrong here. PyCharm doesn't complain if the function just takes the super class or a list of them as an argument, only if it's a Callable, as far as I've seen. For example, neither of the last two lines has a problem.

pslessard
  • 63
  • 8
  • 2
    My brain's fried from work, so this may not be the answer, but see [here](https://stackoverflow.com/questions/56924692/how-to-make-mypy-deal-with-subclasses-in-functions-as-expected). – Carcigenicate Nov 09 '20 at 23:50
  • 2
    Because `Callable` is *contravariant* on its arguments, and covariant on the return type. Read more here: https://www.python.org/dev/peps/pep-0483/#covariance-and-contravariance – juanpa.arrivillaga Nov 10 '20 at 00:05
  • Thank you both. That was really helpful. With my use case, it made more sense for it to work the other way, but the examples in the PEP doc make it pretty clear why it works the other way. I think in my case, I might actually want to use a generic – pslessard Nov 10 '20 at 01:26

1 Answers1

-4

What Python version do you use ? You can submit your issue here : https://youtrack.jetbrains.com/issues/PY

Yezz123
  • 63
  • 4
  • 8