1

I'm pretty sure, this has been asked before, but I don't know, what to search for..

I want to type hint a "generic" function (like a function template in C++)

e.g. (this example makes no sense at all - it's just for demonstration)

def foo(fn: Callable[Any, Any], args: Any) -> Any:
    return fn(args)

I want to use this function in a context where I have full type information, so I hope I can get rid of any Any.

def bar() -> int:
    func: Callable[[str], int] = lambda arg: len(arg)
    return foo(func, "Hurz")

One way of course would be to just explicitly turn foo into (Callable[[str], int], str) -> int, but I'm looking for the generic approach.

I guess what I'm looking for has something to do with generics, but I can't see how to use them to create "function templates".

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
frans
  • 8,868
  • 11
  • 58
  • 132

1 Answers1

1

Python typing has two parts to do what is commonly known as generic programming or parametric polymorphism, or simply "Generics" or "Templates":

Both together form fully parametrisable types such as List[T]. Since functions are inbuilt, the def keyword naturally defines generic types – only TypeVar is needed.

Simply define one TypeVar for each type placeholder needed in a signature:

from typing import TypeVar, Callable

T = TypeVar('T')
R = TypeVar('R')

def foo(fn: Callable[[T], R], args: T) -> R:
    return fn(args)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119