Explain Codes LogoExplain Codes Logo

Can a variable number of arguments be passed to a function?

python
functions
best-practices
error-handling
Nikita BarsukovbyNikita Barsukov·Sep 10, 2024
TLDR

Python offers the *args and **kwargs notations for adapting to variable arguments. Use *args for positional arguments, and **kwargs for keyword arguments.

undefined

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:

def function_with_free_will(arg=None): if arg is not None: # The chosen one has arrived! else: # I guess it's a day off!

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:

try: complicated_function(*too_many_args, **unexpected_kwargs) except TypeError as e: print("Arrgg.. TypeError has boarded! Man your battle stations!", e)

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:

## Too many arguments? Nah, just enough for party! def party1(*args): # First function, first served. def party2(**kwargs): # Second function, second served. args_party_pack = [1, 2, 3] kwargs_confetti = {'x': 4, 'y': 5} party1(*args_party_pack) party2(**kwargs_confetti)

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:

## Chewing through the kwargs, one item at a time! def print_keyword_arguments(**kwargs): for key, value in kwargs.items(): print(f"{key} = {value}")

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!