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
Release: 2024-11-19 09:03:03
Original
1062 people have browsed it

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

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

The corresponding type annotation would be:

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

General Syntax

The general syntax for specifying a function type using "typing.Callable" is:

Callable[[ParamType1, ParamType2, ..., ParamTypeN], ReturnType]
Copy after login

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!

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