I have seen typing.Callable, but I didn't find any useful docs about it. What exactly is typing.Callable?
I have seen typing.Callable, but I didn't find any useful docs about it. What exactly is typing.Callable?
typing.Callable is the type you use to indicate a callable. Most python types that support the () operator are of the type collections.abc.Callable. Examples include functions, classmethods, staticmethods, bound methods and lambdas.
In summary, anything with a __call__ method (which is how () is implemented), is a callable.
PEP 677 attempted to introduce implicit tuple-with-arrow syntax, so that something like Callable[[int, str], list[float]] could be expressed much more intuitively as (int, str) -> list[float]. The PEP was rejected because the benefits of the new syntax were not deemed sufficient given the added maintenance burden and possible room for confusion.
I would like to add to other answers that starting with Python 3.9, typing.Callable is deprecated. You should use collections.abc.Callable instead.
For more details and the rationale, you can take a look at PEP 585
The typing module is used for type hints:
This module provides runtime support for type hints.
The documentation provides this example:
def greeting(name: str) -> str:
return 'Hello ' + name
In the function
greeting, the argument name is expected to be of typestrand the return typestr. Subtypes are accepted as arguments.
typing.CallableAssume you want to define a function that takes two integers and performs some kind of operation on them that returns another integer:
def apply_func(a: int, b: int, func) -> int:
return func(a, b)
So the expected type of the func argument in apply_func is "something that can be called (e.g. a function) that takes two integer arguments and returns an integer":
typing.Callable[[int, int], int]
Using type hints enables you to perform type checking. If you use an IDE like PyCharm or Visual Studio Code, you'll get visual feedback if you're using unexpected types:
See the documentation here.
Short version, Callable is a type hint that indicates a function or other object which can be called.
Consider a simple example below. The bar parameter is a callable object that takes two ints as parameters and returns an int.
>>> def foo(bar: Callable[[int, int], int], a: int, b: int) -> int:
... return bar(a, b)
...
>>> foo(int.__add__, 4, 5)
9
>>> class A:
... def __call__(self, a, b):
... return a * b
...
>>> foo(A(), 6, 7)
42
>>> foo(lambda x, y: x - y, 8, 3)
5
>>>