Reputation: 538
I'm trying to annotate and define my types in python 2.7 using mypy. I can't seem to find any documentation describing how one might pass a function as an argument and record its type. For example, in Scala I can define a function type which maps two ints to a boolean as:
def exampleFunction(f: (Int,Int) => Boolean) = {
// Do Something
}
Is there similar notation in mypy? Something like this perhaps?
def exampleFunction(f):
# type: ((int, int) -> bool) -> None
# Do Something
What is the best practice for annotating function types when they are arguments?
Upvotes: 8
Views: 6754
Reputation: 3815
You could write your function as
from typing import Callable
def exampleFunction(f: Callable[[int, int], bool]):
# Do Something
In general, the syntax is Callable[[<parameters>], <return type>]
Some examples, for 3 possible types of functions
f
with parameters and returndef f(i: int) -> bool:
return i > 0
def check_f(function: Callable[[int], bool]):
...
g
with only returndef g() -> bool:
return True
def check_g(function: Callable[[], bool]):
...
h
with only parametersdef h(i: int, j: int):
pass
def check_h(function: Callable[[int, int], None]):
...
Mypy says: Success: no issues found in 1 source file
Upvotes: 6