Here’s another article in the Functions in Python series. If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
Today we’ll learn how to pass an arbitrary number of both positional and keyword parameters to a function.
If we need both * and ** arguments, the keyword arguments (**) come last:
def company_info(company_name, *cities, **workers):
print(company_name)
print()
if len(cities) > 0:
print("Our company is based in", cities[0])
if len(cities) > 1:
print("We have factories in:")
print()
for city in cities:
print(city)
if len(workers) > 0:
print()
print("Our workers:")
print()
for worker in workers:
print("{} - {}".format(worker.replace("_", " "), workers[worker]))
company_info("Breadmasters", "New York", "Chicago", "Sacramento", "Atlanta", Mike_Harrison = "baker", Tom_Wilkins = "baker", Sue_Earnest = "manager")
And here’s the output:
Breadmasters
Our company is based in New York
We have factories in:
New York
Chicago
Sacramento
Atlanta
Our workers:
Mike Harrison - baker
Tom Wilkins - baker
Sue Earnest - manager
If we try to run the program with different parameters, we’ll get other results. Here are some examples:
– with one * argument and multiple ** arguments
company_info("Breadmasters", "New York", Mike_Harrison = "baker", Tom_Wilkins = "baker", Sue_Earnest = "manager")
The output:
Breadmasters
Our company is based in New York
Our workers:
Mike Harrison - baker
Tom Wilkins - baker
Sue Earnest - manager
– with no * arguments and multiple ** arguments:
company_info("Breadmasters", Mike_Harrison = "baker", Tom_Wilkins = "baker", Sue_Earnest = "manager")
The output:
Breadmasters
Our workers:
Mike Harrison - baker
Tom Wilkins - baker
Sue Earnest - manager
– with multiple * arguments and no ** arguments:
company_info("Breadmasters", "New York", "Chicago", "Sacramento", "Atlanta")
The output:
Breadmasters
Our company is based in New York
We also have factories in:
New York
Chicago
Sacramento
Atlanta
– with just one argument (the mandatory one):
company_info("Breadmasters")
The output:
Breadmasters
If the number of parameters is not fixed, we say the function has indefinite arity. Such functions are sometimes called variadic functions.
In Python we often use the *args and **kwargs notation. So, if we have a function that may take any number of positional and keyword arguments, we write it like so:
our_function(*args, **kwargs)