Python Functions · Lesson 65 of 149

Python Default and Keyword Arguments

What you will learn

  • Default values for parameters
  • Keyword arguments: passing by name, in any order
  • The rules for mixing positional and keyword arguments, and their errors
  • Why a default is worked out once, and the None pattern
  • Keyword-only (*) and positional-only (/) parameters

1. Default values

Give a parameter a default with = in the def line. If the caller leaves that argument out, the default is used:

def greet(name, greeting="Hello", punct="!"):
    return f"{greeting}, {name}{punct}"

print(greet("Rina"))
print(greet("Rina", "Hi"))
print(greet("Rina", "Hi", "?"))
Hello, Rina!
Hi, Rina!
Hi, Rina?

name has no default, so it is required. greeting and punct are optional. Defaults make a function easy to use in the common case and still flexible: greet("Rina") for everyday use, and extra arguments when you need them.

Many built-in functions work this way: round(2.567) rounds to a whole number, while round(2.567, 1) takes the optional second argument.

Quick check: for `def power(base, exponent=2)`, what does `power(5)` give?

25. The missing exponent uses its default, 2.

2. Keyword arguments

In a call, you can give an argument by name, as name=value. These are keyword arguments. They may come in any order, and they make a call self-explaining:

print(greet("Rina", punct="."))
print(greet(name="Sam", greeting="Hey"))
print(greet(punct="?", name="Lee"))
Hello, Rina.
Hey, Sam!
Hello, Lee?

The first call skipped greeting and still set punct. That is impossible with positional arguments alone, unless you also repeat the default. Compare connect("localhost", 8080, True) with connect(secure=True): the second says what True means.

def connect(host="localhost", port=8080, secure=False):
    return f"{'https' if secure else 'http'}://{host}:{port}"

print(connect())
print(connect("example.com"))
print(connect(port=443, secure=True))
print(connect(secure=True))
http://localhost:8080
http://example.com:8080
https://localhost:443
https://localhost:8080

You have used keyword arguments already, in print(..., sep="-", end="!"), sorted(..., reverse=True), max(..., default=0) and int("ff", base=16).

3. The rules for mixing

  1. Positional arguments come first, and then keyword arguments.
  2. Each parameter gets only one value.
  3. A required parameter must be given, by position or by name.
  4. In the def line, parameters with defaults come after those without.
Mistake What you see
a required argument missing greet() missing 1 required positional argument: 'name'
a parameter given twice greet('a', name='b') gives got multiple values for argument 'name'
a name that does not exist greet('a', colour='red') gives got an unexpected keyword argument 'colour'
too many positional arguments greet() takes from 1 to 3 positional arguments but 4 were given
a positional argument after a keyword one SyntaxError: positional argument follows keyword argument
a default before a required parameter SyntaxError: parameter without a default follows parameter with a default
greet("a", name="b")
TypeError: greet() got multiple values for argument 'name'

The first argument "a" already filled name, so giving name="b" too is a clash.

A mixed call is fine when the order is right:

def f(a, b=2, c=3):
    return (a, b, c)

print(f(1), f(1, 5), f(1, c=9), f(c=1, a=0))
(1, 2, 3) (1, 5, 3) (1, 2, 9) (0, 2, 1)

4. A default is worked out once

The default value is calculated when the def line runs, one time, and not on each call:

default_const = 10

def uses_const(x, factor=default_const):
    return x * factor

default_const = 99
print(uses_const(2))
20

Changing default_const afterwards did not change the default, which was fixed as 10 when the function was defined. The same thing makes a current-time default a bug:

import time

def stamp(when=time.time()):
    return when

a = stamp()
time.sleep(0.01)
b = stamp()
print(a == b)
True

Both calls returned the same moment: the time when the function was defined. For a value that must be fresh on each call, use the None pattern: the default is None, and the function makes the real value inside:

def stamp2(when=None):
    if when is None:
        when = time.time()
    return when

a = stamp2()
time.sleep(0.01)
b = stamp2()
print(a == b)
False

The same pattern protects against the mutable-default trap, which lesson 11.9 explains. It is also how you give a default that depends on another parameter:

def area(width, height=None):
    if height is None:
        height = width
    return width * height

print(area(4), area(4, 5), area(4, 0))
16 20 0

area(4) makes a square. Testing is None (and not if not height) keeps area(4, 0) working as 0.

5. See the defaults

A function stores its defaults, and you can look at them with inspect.signature:

import inspect

print(inspect.signature(greet))
print(greet.__defaults__)
(name, greeting='Hello', punct='!')
('Hello', '!')

help(greet) shows the same signature in the shell (lesson 1.4).

6. Keyword-only parameters

A bare * in the parameter list makes every parameter after it keyword-only: the caller must name them. This protects calls with several flags from being read wrongly:

def tag(text, *, bold=False, italic=False):
    out = text
    if bold:
        out = f"<b>{out}</b>"
    if italic:
        out = f"<i>{out}</i>"
    return out

print(tag("hi"))
print(tag("hi", bold=True))
print(tag("hi", italic=True, bold=True))
hi
<b>hi</b>
<i><b>hi</b></i>

tag("hi", True) would be a TypeError. The call must say bold=True, so nobody has to guess what a lone True means.

7. Positional-only parameters

A / in the list makes the parameters before it positional-only: they cannot be named. It needs Python 3.8 or later, and is mostly used by library authors:

def pos_only(a, b, /, c):
    return a + b + c

print(pos_only(1, 2, 3), pos_only(1, 2, c=3))
6 6
pos_only(a=1, b=2, c=3)
TypeError: pos_only() got some positional-only arguments passed as keyword arguments: 'a, b'

Many built-ins work like this: len(obj=[1]) is an error because len takes its argument by position only.

Worked example: a flexible price function

A shop calculates the final price with an optional discount, an optional tax and an optional rounding. The common case is just the price.

def final_price(price, discount=0, tax=0, *, digits=2):
    after_discount = price * (1 - discount / 100)
    with_tax = after_discount * (1 + tax / 100)
    return round(with_tax, digits)

print(final_price(100))
print(final_price(100, 10))
print(final_price(100, tax=15))
print(final_price(80, discount=25, tax=10))
print(final_price(19.99, 5, 8, digits=0))
100.0
90.0
115.0
66.0
21.0
Call Meaning
final_price(100) the defaults: no discount, no tax
final_price(100, 10) 10% discount
final_price(100, tax=15) skip the discount, set only the tax
final_price(80, discount=25, tax=10) both, named, so the call reads clearly
digits=0 keyword-only: you must name it, so 0 cannot be mistaken for a discount

The discounts, tax rates and prices are made up. (digits=0 rounds to a whole number but still gives a float, 21.0.)

Common mistakes

  • Putting a required parameter after a default one in the def line.
  • Giving a parameter two values (positionally and by name).
  • Putting a positional argument after a keyword one.
  • Using a changing value (the current time, a new list) as a default. Use None.
  • Expecting a default to change when the variable it came from changes.
  • Using if not height when 0 is a valid value. Use is None.

Key takeaways

  • def f(x, y=10): gives y a default; parameters with defaults go after those without.
  • A keyword argument f(y=5) names the parameter, so the order does not matter and the call is clearer.
  • Positional arguments come first, then keyword ones; each parameter gets one value.
  • A default is worked out once, when def runs; use None and set the real value inside for fresh or mutable defaults.
  • A bare * makes later parameters keyword-only; / (Python 3.8+) makes earlier ones positional-only.

Practice

1. Write power(base, exponent=2) and call it three ways.

Show answer
def power(base, exponent=2):
    return base ** exponent

power(5)                  # 25
power(5, 3)               # 125
power(exponent=3, base=2) # 8

2. What is wrong with def f(a=1, b):?

Show answer

A parameter without a default (b) follows one with a default. Python reports SyntaxError: parameter without a default follows parameter with a default. Write def f(b, a=1).

3. Why does greet("a", name="b") fail?

Show answer

The first argument already gave name its value, so naming it again gives it two values: TypeError: ... got multiple values for argument 'name'.

4. Why is def add(item, items=[]) a poor default? What should you write?

Show answer

The empty list is created once and shared by every call (lesson 11.9). Use items=None and set items = [] inside when it is None.

5. Make bold keyword-only in def tag(text, bold=False).

Show answer

def tag(text, *, bold=False):. Then tag("hi", bold=True) works, and tag("hi", True) does not.

6. Why is the None pattern better than a default of time.time()?

Show answer

time.time() as a default is worked out once, when the function is defined, so every call would get the same old time. With None, the function reads the clock each time it runs.