Home > Backend Development > Python Tutorial > How do you Define Function Type Hints in Python?

How do you Define Function Type Hints in Python?

Linda Hamilton
Release: 2024-11-15 09:54:02
Original
695 people have browsed it

How do you Define Function Type Hints in Python?

Defining Function Type Hints in Python

In Python, type hints provide a way to specify the expected data types of variables and function arguments and return values. While various types are available for hints, there's no explicit "Function" type. This article presents the solution to specifying function types effectively.

To specify a variable's type hint as a function type, use typing.Callable:

from typing import Callable

def my_function(func: Callable):
    pass
Copy after login

This indicates that the func parameter is expected to be a callable object, such as a function or method.

Note: Callable alone is equivalent to Callable[..., Any], which means it takes any number and type of arguments and returns a value of any type. For a more specific definition, specify the types of input arguments and return values:

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

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

In general, the syntax for a function type hint is:

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

Where ParamType1...ParamTypeN are the types of each parameter, and ReturnType is the expected return type.

The above is the detailed content of How do you Define Function Type Hints in Python?. 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