In Python, you can create functions that accept a wide variety of parameters.
The single-star (*) allows you to accept a varying number of positional arguments:
def get_name(*args):
print('{0} {1} {2}'.format(args[0], args[1], args[2]))
get_name('John', 'A', 'Doe')
The output of running the code above is:
John A Doe
In the get_name function, args will be a tuple containing the values you passed into the function.
The double-star (**) allows you to accept a varying number of keyword arguments (with a name and value) into a dictionary:
def get_name(**kwargs):
print(kwargs['first'], kwargs['middle'], kwargs['last'])
get_name(first='John', last='Doe', middle='A')
The output of running the code is:
John A Doe
How can I pass optional or keyword parameters from one function to another? StackOverflow: *args and **kwargs?
Leave a comment