Specifying Function Type in Type Hints
In Python, type hints are used to provide optional metadata about the expected types of variables and function parameters. However, specifying the type hint of a variable as a function type can seem unclear.
The Solution
Despite the lack of a "typing.Function" in the relevant PEP 483, you can specify the type hint of a variable as a function type using "typing.Callable."
Implementation
The syntax for specifying a function type using "typing.Callable" is as follows:
from typing import Callable def my_function(func: Callable):
Note: Callable on its own is equivalent to "Callable[..., Any]," which means it takes any number and type of arguments and returns a value of any type. If this is too unconstrained, you can further specify the types of the input argument list and return type.
For example, for a function that takes two integers and returns an integer:
def sum(a: int, b: int) -> int: return a b
The corresponding type annotation would be:
Callable[[int, int], int]
General Syntax
The general syntax for specifying a function type using "typing.Callable" is:
Callable[[ParamType1, ParamType2, ..., ParamTypeN], ReturnType]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3