Home >Backend Development >Python Tutorial >How to Specify Function Types in Python Type Hints?

How to Specify Function Types in Python Type Hints?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 09:03:031065browse

How to Specify Function Types in Python Type Hints?

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]

The above is the detailed content of How to Specify Function Types in Python Type Hints?. 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