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
Release: 2024-11-20 19:57:11
Original
619 people have browsed it

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

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

Type Hint:

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

General Syntax

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

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

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!

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