After this lesson you can write a function that takes as many arguments as the caller wants, and you can unpack a list or a dictionary into a call in one step.
The problem
The built-in print accepts one value, or two, or ten. How could you write a function that behaves like that? A fixed list of parameters will not do. Python offers two special parameters for it.
*args: any number of positional arguments
A parameter whose name starts with one star collects all the extra positional arguments into a tuple.
def total(*prices):
print(prices)
return sum(prices)
print(total(10, 20, 5))
print(total())(10, 20, 5)
35
()
0Inside the function prices is an ordinary tuple, so you can loop over it, count it or pass it to sum. With no arguments it is an empty tuple. The traditional name is args, but any name works because the star does the job.
You can combine normal parameters with the star parameter. Normal ones fill first, and the rest goes to the tuple.
def announce(shop, *items):
for item in items:
print(f"{shop}: {item}")
announce("Corner Shop", "milk", "eggs")Corner Shop: milk
Corner Shop: eggs**kwargs: any number of keyword arguments
Two stars collect extra keyword arguments into a dictionary. The keys are the argument names as strings.
def show_details(**details):
print(details)
for key, value in details.items():
print(key, "=", value)
show_details(name="Asha", course="Python", year=2){'name': 'Asha', 'course': 'Python', 'year': 2}
name = Asha
course = Python
year = 2This is handy for functions with many optional settings, or when you want to pass options through to another function.
Using both together
The two can appear in the same definition. The order in the parameter list is: normal parameters, *args, keyword-only parameters, and **kwargs last.
def record(title, *tags, **info):
print("title:", title)
print("tags:", tags)
print("info:", info)
record("Menu", "food", "daily", price=4, vegan=True)title: Menu
tags: ('food', 'daily')
info: {'price': 4, 'vegan': True}Unpacking at the call
The stars have a second job, at the call site. A star in front of a list or tuple spreads its items out as separate arguments. Two stars in front of a dictionary spread it out as keyword arguments.
def volume(length, width, height):
return length * width * height
sizes = [2, 3, 4]
print(volume(*sizes))
box = {"length": 5, "width": 2, "height": 3}
print(volume(**box))24
30This is the reverse of collecting. It is useful when your data is already in a list or dictionary, for example rows read from a file.
You can also use the star to join sequences or print them neatly:
numbers = [1, 2, 3]
print(*numbers)
print(*numbers, sep=" + ")
merged = [*numbers, 4, 5]
print(merged)1 2 3
1 + 2 + 3
[1, 2, 3, 4, 5]Passing arguments through
A common real use is a small wrapper that adds behaviour and then forwards everything unchanged.
def loud_print(*args, **kwargs):
print("LOG:", end=" ")
print(*args, **kwargs)
loud_print("stock low", "tea", sep=" | ")LOG: stock low | teaThe wrapper does not need to know what print accepts. It simply passes everything along. Decorators, which come later in this course, rely on exactly this pattern.
Forcing named options
A star in the parameter list is also useful on its own. Anything after *args can only be given by name. That makes a call self-explanatory, because flags like True always appear beside a label.
def join_words(*words, separator=" ", upper=False):
text = separator.join(words)
return text.upper() if upper else text
print(join_words("fresh", "bread"))
print(join_words("fresh", "bread", separator="-", upper=True))fresh bread
FRESH-BREADHere separator and upper can never be swallowed into words by accident, since a positional argument always goes to the tuple. This design is common in library functions: a variable list of values followed by named options.
Common mistakes
- Forgetting that args is a tuple. You cannot append to it. Convert with
list(args)if you need to change it. - Putting a positional argument after keyword arguments in a call. Positional ones must come first.
- Placing
**kwargsbefore other parameters. It must be last. - Using a single star when you meant two.
f(*box)unpacks only the dictionary keys, not the values. - Overusing it. If a function takes three known values, name the three parameters. Clear names beat a hidden bag of arguments.
A function that does not collect keywords rejects extra ones:
def volume(length, width, height):
return length * width * height
volume(1, 2, 3, colour="red")TypeError: volume() got an unexpected keyword argument 'colour'Exercise
Write a function longest(*words) that returns the longest word it is given. If called with no words it should return an empty string. Test it with "tea", "coffee", "milk".
Show one possible answer
def longest(*words):
best = ""
for word in words:
if len(word) > len(best):
best = word
return best
print(longest("tea", "coffee", "milk"))
print(repr(longest()))coffee
''Key points
- *args collects extra positional arguments into a tuple.
- **kwargs collects extra keyword arguments into a dictionary.
- The names args and kwargs are only a convention. The stars are what matter.
- At the call, *items unpacks a sequence and **options unpacks a dictionary into separate arguments.
- In the parameter list the order is normal parameters, *args, keyword-only parameters, then **kwargs.