Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify the function type in my type hints?

People also ask

Can you specify type in Python?

Python is a strongly-typed dynamic language in which we don't have to specify the data type of the function return value and function argument. It relates type with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions.

What does the function type () do?

The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.

What is the function type in Python?

The type() function in Python returns the data type of the object passed to it as an argument. This function is very useful in the debugging process​.

How do you define a type in Python?

Specify a Variable Type Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)


As @jonrsharpe noted in a comment, this can be done with typing.Callable:

from typing import AnyStr, Callable

def my_function(name: AnyStr, func: Callable) -> None:

Issue is, Callable on it's own is translated to Callable[..., Any] which means:

A callable takes any number of/type of arguments and returns a value of any type. In most cases, this isn't what you want since you'll allow pretty much any function to be passed. You want the function parameters and return types to be hinted too.

That's why many types in typing have been overloaded to support sub-scripting which denotes these extra types. So if, for example, you had a function sum that takes two ints and returns an int:

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

Your annotation for it would be:

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]

Another interesting point to note is that you can use the built in function type() to get the type of a built in function and use that. So you could have

def f(my_function: type(abs)) -> int:
    return my_function(100)

Or something of that form


An easiest and fancy solution is:

def f(my_function: type(lambda x: None)):
    return my_function()

This can be proved in the following way:

def poww(num1, num2):
    return num1**num2
    
print(type(lambda x: None) == type(poww))

and the output will be: True