Home >Backend Development >Python Tutorial >How Can I Specify Function Types in Python Annotations Using `typing.Callable`?

How Can I Specify Function Types in Python Annotations Using `typing.Callable`?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 20:55:13371browse

How Can I Specify Function Types in Python Annotations Using `typing.Callable`?

Specifying Function Types in Annotations

Within Python type hinting, expressing a variable's type as a function is essential for ensuring code correctness. Despite the lack of an explicit typing.Function type annotation, there is a solution using typing.Callable.

Using typing.Callable for Function Types

As @jonrsharpe pointed out, typing.Callable allows us to define function types in annotations. For example:

from typing import Callable

def my_function(func: Callable):

Here, the variable func is type-hinted as a function that accepts any number and type of arguments and returns a value of any type.

Specifying Input and Return Types

For more precise annotations, we can further specify the types of input arguments and the return type of the function. Consider the following example:

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

The corresponding annotation would be:

Callable[[int, int], int]

This indicates that the function accepts two integer arguments and returns an integer.

General Syntax

In general, the syntax for function type annotations in Python is:

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

Where:

  • ParamType1, ..., ParamTypeN are the types of the input arguments
  • ReturnType is the type of the return value

By leveraging typing.Callable, we can effectively specify function types in Python type annotations, improving code readability and ensuring type correctness.

The above is the detailed content of How Can I Specify Function Types in Python Annotations Using `typing.Callable`?. 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