Can a variable number of arguments be passed to a function?
Python offers the *args
and **kwargs
notations for adapting to variable arguments. Use *args
for positional arguments, and **kwargs
for keyword arguments.
When life gives you arguments, make function with *args
def print_args(*args): for arg in args: print(arg)
print_args('apple', 'banana', 'cherry')
Keywords are key to your happiness? **kwargs to the rescue!
def print_kwargs(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
print_kwargs(first='apple', second='banana')
## Peeling the `*args` and `**kwargs` layers
To make your Python code more **readable** and **maintainable**, follow these guidelines:
### Maintain the order of parameters
In a function definition, parameters should be arranged as follows: mandatory **positionals**, `*args`, default **keywords**, and `**kwargs`:
```python
def function(positional_args, *args, keyword_args=default_value, **kwargs):
# Our magical function that accepts all!
Use None
for optional arguments
When grepping for optional arguments, make None
your ally. It helps to clearly mark unspecified arguments:
Debug efficiently with error messages
Good error handling makes your functions user-friendly. When you run into trouble with *args
and **kwargs
, the error message is your first clue to TypeError
treasure:
Power-ups and pitfalls
Distributing arguments to multiple functions
When dealing with multiple functions and a set of *args
and **kwargs
, scatter them with lists or dictionaries:
Brace for runtime errors
Even though Python doesn't have compiler errors like some other languages, that doesn't mean it's a smooth sail. Typing errors (TypeError
) and mismatches (ValueError
) are pirates waiting to raid your *args
and **kwargs
ship!
Dictionaries for keyword arguments
Meet Python 3 items()
, your handy helper for iterating keywords in **kwargs
dictionaries:
Various languages, various ways
Different languages handle variable number of arguments in their own ways. So, don't forget to check out 'variadic functions' Greek flavor if you're coding in other languages!
Was this article helpful?