Specifying Function Types in Annotations
Within Python type hinting, expressing a variable's type as a function is essential for ensuring code correctness. Despite the lack of an explicit typing.Function type annotation, there is a solution using typing.Callable.
Using typing.Callable for Function Types
As @jonrsharpe pointed out, typing.Callable allows us to define function types in annotations. For example:
from typing import Callable def my_function(func: Callable):
Here, the variable func is type-hinted as a function that accepts any number and type of arguments and returns a value of any type.
Specifying Input and Return Types
For more precise annotations, we can further specify the types of input arguments and the return type of the function. Consider the following example:
def sum(a: int, b: int) -> int: return a + b
The corresponding annotation would be:
Callable[[int, int], int]
This indicates that the function accepts two integer arguments and returns an integer.
General Syntax
In general, the syntax for function type annotations in Python is:
Callable[[ParamType1, ParamType2, ..., ParamTypeN], ReturnType]
Where:
By leveraging typing.Callable, we can effectively specify function types in Python type annotations, improving code readability and ensuring type correctness.
The above is the detailed content of How Can I Specify Function Types in Python Annotations Using `typing.Callable`?. For more information, please follow other related articles on the PHP Chinese website!