Lesson 5 of 16 · Functions in Depth
Default and Keyword Arguments
Learn Python default values and keyword arguments, how to make calls clearer, the mutable default trap and how to force keyword-only arguments.
- 7 min read
- Intermediate
- Reviewed
- How to give a parameter a default value
- How to pass arguments by name to make calls clear
- Why a list or dictionary should never be a default value
- How to require that some arguments are named
Default values
A default value makes a parameter optional. If the caller leaves it out, the default is used.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Grace", "Welcome"))greeting has the default "Hello". The first call does not mention it, so the default is used. The second call supplies its own value.
Parameters with defaults must come after the ones without. def greet(greeting="Hello", name) is a syntax error, because Python could not tell which value goes where.
Keyword arguments
So far you have passed arguments by position: the first value goes to the first parameter, and so on. You can also pass them by name. These are called keyword arguments.
def make_course(title, level="Beginner", hours=10, free=True):
return f"{title} | {level} | {hours} h | {'free' if free else 'paid'}"
print(make_course("Python Intermediate", hours=14, level="Intermediate"))
print(make_course("SQL for Beginners", free=True))Keyword arguments have two big advantages:
- Clarity.
hours=14says what 14 means. A bare14does not. - Freedom of order and choice. You can give them in any order and skip the ones whose defaults are fine.
Compare these two calls. The second one explains itself.
train(data, 10, 0.001, True)
train(data, epochs=10, learning_rate=0.001, shuffle=True)Mixing both kinds
You can combine positional and keyword arguments, as long as the positional ones come first.
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(5, 3))
print(power(5, exponent=3))
print(power(base=2, exponent=10))The mutable default trap
This is one of the most famous surprises in Python. Watch what happens when the default value is a list.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("sql"))You might expect ['sql'] on the second line. Instead, the first tag is still there.
The reason: a default value is created once, when the function is defined, not each time it is called. Every call that uses the default shares the same list, so it keeps growing.
The fix is to use None as the default and create a new list inside the function.
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("python"))
print(add_tag("sql"))The rule: never use a list, dictionary or set as a default value. Use None and create it inside.
Requiring names: keyword-only arguments
Sometimes an argument is so easy to confuse that you want callers to always name it. Put a * in the parameter list. Everything after it must be passed by name.
def transfer(amount, *, from_account, to_account):
print(f"Moving {amount} from {from_account} to {to_account}")
transfer(500, from_account="savings", to_account="current")Calling transfer(500, "savings", "current") would now stop with a TypeError. That is the point: nobody can swap the two accounts by accident.
Common mistakes
Write a function with two default values, then call it with keyword arguments.
# Write a function called price_label(price, currency="INR", discount=0)
# that returns text like "INR 450.00".
# The discount is a percentage taken off the price.
# Use 2 decimal places: f"{value:.2f}"
print(price_label(500))
print(price_label(500, discount=10))
print(price_label(20, currency="USD"))
# Output must be exactly:
# INR 500.00
# INR 450.00
# USD 20.00
Why is def add(item, items=[]) a problem?
Summary
def f(x, y=10)givesya default value, which makes it optional.- Keyword arguments,
f(x, y=5), make calls clearer and can be given in any order. - Never use a list, dictionary or set as a default. Use
Noneinstead. - A
*in the parameter list makes the following parameters keyword-only.
Next: functions that accept any number of arguments.
Finished reading? Tick it off to track your progress.