Home >Backend Development >Python Tutorial >How to Specify Function Types in Type Hints with `typing.Callable`?

How to Specify Function Types in Type Hints with `typing.Callable`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-23 02:05:13549browse

How to Specify Function Types in Type Hints with `typing.Callable`?

Specifying Function Types in Type Hints

In type hints, specifying the type of a variable as a function might seem challenging without a dedicated "typing.Function" class or guidance in PEP 483. However, the solution lies in utilizing "typing.Callable."

By leveraging "typing.Callable," you can declare function types in your annotations. For instance:

from typing import Callable

def my_function(func: Callable):

It's important to note that "Callable" by itself is equivalent to "Callable[..., Any]." This implies that the callable function accepts any number and type of arguments (...) and returns a value of any type (Any).

If you require stricter constraints, you can specify the input argument types and return type explicitly. For example, consider the function "sum":

def sum(a: int, b: int) -> int: return a+b

Its corresponding annotation would be:

Callable[[int, int], int]

In this annotation, the parameters are specified within the square brackets, and the return type is specified as the second element within the square brackets. The syntax for specifying function types in general is:

Callable[[ParamType1, ParamType2, ..., ParamTypeN], ReturnType]

The above is the detailed content of How to Specify Function Types in Type Hints with `typing.Callable`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn