*args and **kwargs
PronunciationARGZ and KWARGZ
Definition
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary, so a function can accept any number of them.
Where you hear it
In Python tutorials, decorators and wrapper functions, and library code that forwards arguments to another function.
Examples
The wrapper takes
*args, **kwargsand passes them straight to the original function.total(*numbers)accepts any number of values.The decorator accepts args and kwargs, so it works with any function signature
Common mistake
Using them everywhere. Clear named parameters are easier to read and document than a hidden bag of arguments.
Don't confuse with
Unpacking at the call site: f(*items) spreads a list into arguments, while def f(*items) collects them.
Say it at work
- In a meeting or chat
Accept
**kwargsand forward them to the parent class. - In an email or ticket
I'd rather list the real parameters than hide them in kwargs.
Keep exploring
More in Programming Fundamentals