How do you add type hints for a function with specific keyword arguments?

Viewed 1624

I want to add type hints to a higher order function whose input (also a function) has specific keyword arguments.

My code looks similar to this:

def foo(a: int, b: int) -> int:
    ...


def bar(c: Callable[[int, int], int]) -> int:
    return c(a=1, b=2)  # getting a mypy error: Unexpected keyword argument "a"

In the example, I want to be able to call c from the function scope of bar, and I want to be able to assume it has keyword arguments a and b.

I can see why mypy would complain here, since some other function with a different signature could be passed in as an argument to b and then c(a=1, b=2) would no longer work. But it seems like there should be a way to add the keyword argument names in the type hint, to explicitly guarantee that function c takes arguments with names a and b.

1 Answers

There is the mypy extension for extending Callable

from typing import Callable
from mypy_extensions import (Arg, DefaultArg, NamedArg,
                             DefaultNamedArg, VarArg, KwArg)
                             
def foo(a: int, b: int) -> int:
    ...


def bar(c: Callable[[Arg(int, 'a'), Arg(int , 'b')], int]) -> int:
    return c(b=1, a=2)  # no issues
Related