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
Release: 2024-11-23 02:05:13
Original
511 people have browsed it

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):
Copy after login

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
Copy after login

Its corresponding annotation would be:

Callable[[int, int], int]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template