nbertagnolli
nbertagnolli

Reputation: 538

Can you define a type for a function as an argument in python using mypy?

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

Answers (1)

charelf
charelf

Reputation: 3815

Short answer:

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>]

More examples:

Some examples, for 3 possible types of functions

  1. function f with parameters and return
def f(i: int) -> bool:
    return i > 0

def check_f(function: Callable[[int], bool]):
    ...
  1. function g with only return
def g() -> bool:
    return True

def check_g(function: Callable[[], bool]):
    ...
  1. function h with only parameters
def 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

Related Questions