How can I specify the function type in my type hints?
To type hint your Python functions, use the typing.Callable class:
The Callable[[Arg1Type, Arg2Type], ReturnType] class defines the callback function to accept an int and a str, and return a float.
Upgrade your Callable game
The basic usage of Callable is intuitive: each argument type in the square brackets, and return type, right? But sometimes, you might need something fancier.
For instance, Python 3.8 introduced Protocol from typing to allow specification of more sophisticated function arguments:
Above, any object passed to close_resource should have a close method. Much like all of us need a close method. Hers was just too abrupt...
Space-saving with variadic generics
Python 3.9+ further ups the game introducing variadic generics. This way, you can specify callbacks with any number of arguments. All using the well-named ParamSpec object:
The joys and woes of Type Hints
In the wild world of Python, functions come in different shapes and sizes. Here's how you can apply type hints in different situations:
Anonymous but useful: Lambdas
For lambdas or functions sans clear signature, Callable[..., ReturnType] is your catch-all:
Your functions need band-aids? Go partial!
When leveraging functools.partial, remember to tailor your Callable to reflect the remaining arguments:
For the minimalists: Callable without imports
Avoid Callable to keep it simple. Granted, it's like shooting in the dark, but at least you didn't have to import anything:
For the curious minds: Function introspection
Determine the function's type via introspection using type(), and you can specify type hints without guessing:
Was this article helpful?