After this lesson you can make some arguments optional, call a function by naming its arguments, and avoid a well-known bug involving default values.
Default values
Sometimes most callers want the same value for a parameter. You can write that value into the definition with an equals sign. If the caller leaves the argument out, the default is used.
def total_with_tax(amount, tax_rate=0.18):
return round(amount * (1 + tax_rate), 2)
print(total_with_tax(100))
print(total_with_tax(100, 0.05))118.0
105.0The first call supplies one argument, so tax_rate is 0.18. The second overrides it. Defaults make functions pleasant to call: the common case is short, and the unusual case is still possible.
Order rules
Parameters without defaults must come first. Python refuses the opposite order:
def broken(rate=0.18, amount):
return amount * rateSyntaxError: non-default argument follows default argumentPython stops at the definition itself, before anything can be called. Always list required parameters first, optional ones after.
Keyword arguments
At the call you can name each argument. These are called keyword arguments, and they have two benefits. The order no longer matters, and the call reads like a sentence.
def describe_book(title, author, year=2020):
return f"{title} by {author} ({year})"
print(describe_book("Rivers", "M. Das"))
print(describe_book(author="M. Das", title="Rivers", year=1999))
print(describe_book("Rivers", year=2005, author="M. Das"))Rivers by M. Das (2020)
Rivers by M. Das (1999)
Rivers by M. Das (2005)You can mix both styles, but positional arguments must come before keyword ones in the call. Compare a bare call such as send(True, 3, 5) with send(urgent=True, retries=3, delay=5). The second explains itself, so use keywords whenever a value's meaning is not obvious.
Passing the same parameter twice is an error:
describe_book("Rivers", "M. Das", author="Someone Else")TypeError: describe_book() got multiple values for argument 'author'Default values are created once
This is the most famous trap in the lesson. A default value is built once, when the def line runs, and then reused by every call. For numbers and strings this is harmless because they cannot be changed. For a list it causes surprises:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("bread"))['apple']
['apple', 'bread']You might expect the second line to show only bread. Instead both calls changed the same hidden list. The usual fix is to use None as the default and create a fresh list inside:
def add_item_safe(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item_safe("apple"))
print(add_item_safe("bread"))['apple']
['bread']Now every call starts with its own empty list. Remember this pattern: when the default should be a list, dictionary or set, write None and build it inside.
Positional-only and keyword-only parameters
Two small symbols in the parameter list control how arguments may be passed. A bare * means everything after it must be given by name:
def make_label(text, *, upper=False):
return text.upper() if upper else text
print(make_label("sale", upper=True))SALECalling make_label("sale", True) would fail, because upper is keyword-only. This protects callers from mixing up yes and no flags. A / does the opposite for parameters before it, making them positional-only. Both are optional tools; you will meet them mostly in library code.
Designing a friendly function
Defaults and keywords work best together. Put the arguments that nearly every caller must supply first, and give sensible defaults to the rest. Then a typical call stays short, and an unusual call names only the settings that differ.
def make_invoice(customer, items, currency="INR", discount=0, note=""):
total = sum(items) - discount
line = f"{customer}: {total} {currency}"
return line + (f" ({note})" if note else "")
print(make_invoice("Asha", [100, 50]))
print(make_invoice("Ben", [100, 50], discount=20, note="festival offer"))
print(make_invoice("Chloe", [80], currency="USD"))Asha: 150 INR
Ben: 130 INR (festival offer)
Chloe: 80 USDLook at how readable the calls are. A reader understands discount=20 immediately, whereas a bare 20 in the fourth position would need a trip to the definition. When a function has more than two or three optional settings, encourage callers to name them.
Common mistakes
- A mutable default such as
[]or{}. UseNoneinstead. - Required parameter after an optional one. Python rejects it.
- Giving an argument twice, once by position and once by keyword.
- Misspelling a keyword. The name must match the parameter exactly, or you get a
TypeErrorabout an unexpected keyword argument. - Expecting a default to change. A default is fixed when the function is defined, not each time it is called.
Exercise
Write a function shipping_cost(weight, rate=5, express=False) that returns weight * rate, doubled when express is true. Call it three ways: only with weight 3, with weight 2 and express=True, and with all three arguments by keyword.
Show one possible answer
def shipping_cost(weight, rate=5, express=False):
cost = weight * rate
if express:
cost = cost * 2
return cost
print(shipping_cost(3))
print(shipping_cost(2, express=True))
print(shipping_cost(weight=4, rate=6, express=True))15
20
48Key points
- A default value, written def f(x=10), makes that argument optional.
- Keyword arguments, written f(x=5), pass values by name, so the order no longer matters.
- Parameters with defaults must come after parameters without defaults.
- Never use a list or dictionary as a default value. Use None and create the object inside the function.
- A / and * in the parameter list can force positional-only or keyword-only arguments.