Function definitions can specify parameters in several ways. Choosing the right form makes calls readable and prevents bugs.
Positional arguments#
def describe(name, age, city):
return f"{name} is {age} and lives in {city}"
print(describe("Ada", 36, "London"))Arguments are matched left to right. A wrong order produces wrong results without necessarily raising an error.
Keyword arguments#
print(describe(age=36, city="London", name="Ada"))Keyword arguments are matched by name, so order does not matter. They are especially useful for calls with several boolean or numeric parameters where positions are hard to remember.
A call may mix positional and keyword arguments, but positional arguments must come first:
print(describe("Ada", city="London", age=36))Default values#
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(5, 3)) # 125
print(power(2, exponent=10)) # 1024Parameters with defaults must come after parameters without defaults. Defaults are evaluated once, when the function is defined.
Keyword-only arguments#
Put * in the parameter list to require keyword arguments for everything after it:
def connect(host, *, timeout=30, retries=3):
return f"{host}: timeout={timeout}, retries={retries}"
print(connect("example.com", timeout=10))
# connect("example.com", 10) # TypeErrorThis prevents confusing positional calls when several parameters share a type.
*args#
*args collects extra positional arguments into a tuple:
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4))The name args is a convention; what matters is the *. Inside the function, numbers is a tuple.
**kwargs#
**kwargs collects extra keyword arguments into a dictionary:
def show_settings(**options):
for key, value in options.items():
print(f"{key} = {value}")
show_settings(theme="dark", font_size=14)The name kwargs is also a convention. These tools are useful for wrappers and configuration, but a function that accepts arbitrary options can be hard to document. Prefer explicit parameters when the set is known.
The mutable default trap#
Do not use a mutable object as a default:
def add_item(item, items=[]): # BUG: list shared across calls
items.append(item)
return itemsThe default list is created once. Every call that omits items reuses the same list. Use None as the sentinel:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsThis creates a fresh list for each call when no list is supplied.
Unpacking arguments at the call site#
Use * and ** to pass an existing sequence or mapping:
def area(width, height):
return width * height
dimensions = (3, 4)
print(area(*dimensions))
options = {"width": 5, "height": 6}
print(area(**options))This is common when forwarding arguments to another function.
Practice#
Write a function format_price(amount, currency="USD", *, decimals=2) that returns a formatted string. Call it with defaults, with a positional currency, and with keyword arguments. Then write a function that accepts any number of scores with *scores and returns the highest and average.
