capypad
0 day streak
python / intermediate
Snippet

Unpacking with *args and **kwargs

*args allows a function to accept any number of positional arguments as a tuple, while **kwargs accepts arbitrary keyword arguments as a dictionary.

snippet.py
python
1
2
3
4
5
6
def versatile_func(required, *args, **kwargs):
print(f'Required: {required}')
print(f'Additional positional: {args}')
print(f'Keyword arguments: {kwargs}')
 
versatile_func('Main', 1, 2, mode='fast', debug=True)
Breakdown
1
*args
Collects extra positional arguments into a tuple named 'args'.
2
**kwargs
Collects extra keyword arguments into a dictionary named 'kwargs'.