Python Tutorial · Functions · Lesson 24 of 42

Python Function Arguments

Default values, keyword arguments, *args, **kwargs and keyword-only parameters.

Default and keyword arguments

Example 1Try it yourself
def power(base, exponent=2):
    return base ** exponent

print(power(3))
print(power(3, 3))
print(power(exponent=3, base=2))

Output

9
27
8

*args and **kwargs

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

Example 2Try it yourself
def total(*numbers):
    return sum(numbers)

def describe(**info):
    for key, value in info.items():
        print(f"{key} = {value}")

print(total(1, 2, 3, 4))
describe(name="Ada", role="engineer")
nums = [5, 6]
print(total(*nums))

Output

10
name = Ada
role = engineer
11

Keyword-only and positional-only parameters

Parameters after * must be passed by name; parameters before / must be passed by position. This makes call sites clearer:

Example 3Try it yourself
def connect(host, port, *, timeout=5, retries=3):
    return f"{host}:{port} timeout={timeout} retries={retries}"

print(connect("db", 5432, timeout=10))
try:
    connect("db", 5432, 10)
except TypeError as e:
    print("TypeError:", e)

Output

db:5432 timeout=10 retries=3
TypeError: connect() takes 2 positional arguments but 3 were given

The mutable default trap

Default values are evaluated once, when the function is defined. Never use a mutable default like []:

Example 4Try it yourself
def add_item(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(add_item(1))
print(add_item(2))   # a fresh list each time

Output

[1]
[2]

Test yourself

What type is args inside def f(*args)?

  1. list
  2. tuple
  3. dict
  4. set
Show answer

Answer: tuple