Issue
How can I specify the type hint of a variable as a function type? There is no typing.Function, and I could not find anything in the relevant PEP, href="https://www.python.org/dev/peps/pep-0483/" rel="noreferrer">PEP 483.
Solution
As @jonrsharpe noted in a comment, this can be done with typing.Callable:
from typing import Callable
def my_function(func: Callable):
Note: Callable on its own is equivalent to Callable[..., Any].
Such a Callable takes any number and type of arguments (...) and returns a value of any type (Any). If this is too unconstrained, one may also specify the types of the input argument list and return type.
For example, given:
def sum(a: int, b: int) -> int: return a+b
The corresponding annotation is:
Callable[[int, int], int]
That is, the parameters are sub-scripted in the outer subscription with the return type as the second element in the outer subscription. In general:
Callable[[ParamType1, ParamType2, .., ParamTypeN], ReturnType]
Answered By - Dimitris Fasarakis Hilliard Answer Checked By - David Marino (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment