Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python 3.5, how can I specify a function as a type hint?

What is the appropriate type hint to specify that a variable should be a function (the equivalent of a delegate, Func<T> or Action in C#)?

Is it also possible to specify the function argument types in a generic fashion as well (for example Func<int, int>)?

I cannot find any relevant details in the documentation.

like image 437
Erwin Mayer Avatar asked Feb 10 '16 12:02

Erwin Mayer


People also ask

How do you type a hint in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

Does Python 3.6 support type hints?

This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any , Union , Tuple , Callable , TypeVar , and Generic . For full specification please see PEP 484.

Can you specify type in Python?

Specify a Variable Type There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

What is type () in Python?

The type() function is used to get the type of an object. Python type() function syntax is: type(object) type(name, bases, dict)


1 Answers

According to the docs, you can use Callable, imported from typing.

You can view more details in PEP 0484.

like image 63
Mike Lawson Avatar answered Oct 22 '22 08:10

Mike Lawson