Why can I not use `function` in type hints, as I can use `int`, `str` and `list`? [duplicate]
I want to use type hints in my current Python 3.5 project. My function should receive a function as parameter.
How can I specify the type function in my type hints?
import typing
def my_function(name:typing.AnyStr, func: typing.Function) -> None:
# However, typing.Function does not exist.
# How can I specify the type function for the parameter `func`?
# do some processing
pass
I checked PEP 483, but could not find a function type hint there.
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 int
s 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
My specific use case for wanting this functionality was to enable rich code completion in PyCharm. Using Callable
didn't cause PyCharm to suggest that the object had a .__code__
attribute, which is what I wanted, in this case.
I stumbled across the types
module and..
from types import FunctionType
allowed me to annotate an object with FunctionType
and, voilà, PyCharm now suggests my object has a .__code__
attribute.
The OP wasn't clear on why this type hint was useful to them. Callable certainly works for anything that implements .__call__()
but for further interface clarification, I submit the types
module.
Bummer that Python needed two very similar modules.