Type annotations for *args and **kwargs
For type annotation of *args
, use single-type Type
or multi-type Union[Type1, Type2]
, and for **kwargs
, use Dict[KeyType, ValueType]
. For varied types apply Any
.
To transcend towards Python 3.10+ for granular control, embrace ParamSpec
.
Making sense of protocols and ABCs
Wait, is your *args
and **kwargs
fulfill a certain protocol or an ABC (Abstract Base Classes) interface? Protocol
and ABCs with type annotations are your saviors. They're like the cleaning crew, making your code sparkling clean and its intent more readable.
The magic of function overloading
@overload
rounds up different combinations of *args
wrapping them into various return types. It's the whisperer for your type checker, hinting about the varying sets of parameters your function is friendly with.
The power typing of *args and **kwargs with TypedDict and Unpack
Take your **kwargs
typing to new heights using TypedDict for defining expected types. It's as if you added a turbo charger for your type checking:
In Mypy 0.981+ or higher, you'll find Unpack
waiting for activation with the --enable-incomplete-features
flag:
Conventions and obstacles with *args and **kwargs
Dealing with *args
Remember, *args
is a ravenous creature - it takes an unlimited number of arguments. What’s that mean? You cannot limit the number of int
inputs:
Mixed bag of argument types
What if *args
takes mixed types? Go with object
and employ type narrowing through runtime checks to maintain peace:
Enforcing signatures
As of Python 3.10, you can be the traffic warden for types with ParamSpec
. It lets you declare types of *args
and **kwargs
:
Python 2 considerations
While Python 2 doesn’t natively support type hints, use type comments are your rescue flare:
Was this article helpful?