3

Before 3.9 I would have used this:

from typing import Callable

def my_function(argument_function: Callable) -> None:

Now I am not sure anymore.

PEP 585 has a list of deprecated Typing-types that does not include typing.Callable but does include collections.abc.Callable. So far I haven't use the collections.abs module but I wonder if typing.Callable might be related to collections.abc.Callable therefore making the Callable type hint deprecated, too.

I did try this:

def my_function(argument_function: callable) -> None:

And it works.

But is that really the correct way now? Or Do I still have to import typing.Callable?

sophros
  • 14,672
  • 11
  • 46
  • 75
jfl21
  • 39
  • 4
  • 1
    No, `callable` isn't a type. – juanpa.arrivillaga Apr 01 '21 at 09:40
  • 1
    If they intended to deprecate typing.Callable they would have deprecated typing.Callable. That PEP is specifically about reducing the amount of redundancy - they don't want two Callables in two different places that mean the same thing. – Kemp Apr 01 '21 at 09:40
  • 1
    "And it works." What do you mean by "it works"? It certainly isn't accepted by, say, `mypy` and it is definitely not part of the specification – juanpa.arrivillaga Apr 01 '21 at 09:41
  • It works means: PyCharm doesn't give me a warning and treats "function: callable" the same way it treats "number: int" or "string: str". Also the code runs. – jfl21 Apr 01 '21 at 09:49
  • 2
    That doesn't mean much. The code would *run* you used anything, e.g. `def my_function(argument_function: sum) -> None:` even though `sum` isn't a valid type annotation. If you check the above with mypy, the semi-official static type checker, you'd get `error: Function "builtins.callable" is not valid as a type`... because as I stated earlier, `callable` *isn't a type* – juanpa.arrivillaga Apr 01 '21 at 09:54
  • Alright. Thanks. Just for clarification: `import typing: Callable` is still the way to go then? – jfl21 Apr 01 '21 at 09:57
  • 6
    Yes, and you probably should be using the fll form, `Callable[[ArgTypes], ReturnType]` – juanpa.arrivillaga Apr 01 '21 at 09:59

1 Answers1

1

Since there isn't an answer, I'm elevating juanpa.arrivillaga's comment to an answer. Quoting the above comment [sic]:

you probably should be using the fll form, Callable[[ArgTypes], ReturnType]

Or fleshing it out:

from typing import Callable

# Let's say this was an example of argument_function and that's 
# the signature that you expect in my_function

def foo(x: int) -> str:
    return str(x)

def my_function(argument_function: Callable[[int], str]) -> None:
    pass