Arguments
Keyword arguments, default values, *args.
Arguments can be passed by position or by name. Keyword arguments make a call clearer and let you change the order:
def greet(name, greeting="Hi"):
return f"{greeting}, {name}"
print(greet("Ann")) # Hi, Ann
print(greet("Ann", greeting="Hey")) # Hey, Ann
greeting has a default value, so it can be left out. Parameters with default values come after the required ones.
A default value is computed once, when the function is declared. With mutable values this is a trap:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b']
The second call "remembers" the first, because the default list is one and the same for all calls. The correct pattern is items=None in the declaration and if items is None: items = [] at the start of the body.
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary:
def total(*prices, discount=0):
return sum(prices) - discount
print(total(100, 50)) # 150
print(total(100, 50, discount=30)) # 120
A parameter that comes after *prices can only be passed by name. This protects against the mistake of passing the discount as just another price. The asterisk also works in a call: total(*[10, 20]) spreads a list into separate arguments.
Practice
A keyword argument
What does the program print?
def greet(name, greeting="Hi"): return f"{greeting}, {name}" print(greet("Ann", greeting="Hey"))A default list
Why is it dangerous to write def add(item, items=[])?
- The list is created once and shared by all calls
- Python forbids lists in parameters
- The list is empty on every call
- The function cannot return a list
A total with a discount
Write a function total(*prices, discount=0) that returns the sum of all the prices passed, minus discount. The discount can only be passed by name.