Python’s *args and **kwargs demistified

When reading other’s code, most beginners are puzzled by the use and meaning of these terms and I believe this is the post to end it all.

So take away any confusion you might have been facing allow me start with this, the terms “args” and “kwargs” mean nothing. Any variable name can be used. eg;- *vars, **kvars. The only useful/meaning/necessary section to the python interpreter is the asterisk ‘*’. The terms “args” and “kwargs” are just a convention.

*args and **kwargs are magic variables used in function definitions. They allow a user to pass an unspecified number of arguments to a function. Therefore, when writing a function, you don’t need to know how many variables will be passed to your function.

Usage of *args:

It is used to send non-key worded variable length argument list to a function. For example;

Output for the code above will be

Normal variable is: Spike.
The rest are:

Usage of **kwargs:

This one is used to pass key worded variables length arguments to a function. You will mainly use it if you want use named arguments in a function. For example;

Output for the code aseperatebove will be

first_name: Micheal
middle_name: B
last_name: Jordan

Note: If you want to use them at the same time in a function, they have a specific order,

random_func(fargs, *args, **kwargs)

When to use them:

The common question after learning something is when will I apply it. Frankly, it depends on your software/algorithm requirements. They are commonly used when making function decorator, which will be covered in a separate blog post. They can also be used in ‘monkey patching’ as well. Monkey patching means modifying some code at runtime.

Bottom line, they are useful when you in doubt about the number of arguments your function will/should accept/use.

Self-taught programmer with focus on web, deep learning and Artificial Intelligence as a whole.