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

How to Specify Function Types with Type Hints in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 19:57:11637browse

How to Specify Function Types with Type Hints in Python?

How to Designate Function Types in Type Hints

In Python, specifying type hints for function variables can be done using typing.Callable.

Function Parameter Specification

To specify the type hint of a variable as a function, use the following syntax:

from typing import Callable

def my_function(func: Callable):

Input and Output Type Definition

The Callable type can be further refined to specify the types of input and output parameters:

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

Type Hint:

Callable[[int, int], int]

General Syntax

The general syntax for specifying a function type in a type hint is:

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

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