Legends ofPythos
Claim your name
Writing Real Programs

Positional-only and keyword-only parameters

Lesson 5 of 16

Watch the lesson5:43 · with Sigrid
You already know that you can call a function by passing values in order, or by naming the parameter. A function's signature is its def line: its name and its parameters. Python gives you two extra tools to make signatures safer: positional-only and keyword-only parameters.

Keyword-only with *

Put a bare * in the signature. Every parameter after it must be passed by keyword.
def tea(kind, *, sugar=0, milk=False):
    return f'{kind} | s={sugar} m={milk}'

print(tea('mint'))
# mint | s=0 m=False

print(tea('mint', milk=True))
# mint | s=0 m=True
tea('mint', True) now raises TypeError. Without the *, that True would quietly land in sugar, the next place in line: no error, just the wrong tea. Now the caller has to name the option they mean: tea('mint', milk=True).

Positional-only with /

def area(width, height, /):
    return width * height

print(area(4, 5))   # 20
# print(area(width=4, height=5))  -> TypeError
/ says: parameters before it are matched by position only. Callers can't use the names width and height, so you can rename them later without breaking any call like area(4, 5).

Reading real signatures

# How Python's help pages write sorted():
#   sorted(iterable, /, *,
#          key=None, reverse=False)
# iterable is before the /: by position only.
# key and reverse are after the *: by name only.

scores = [3, 9, 5]
print(sorted(scores, reverse=True))
iterable (anything you can loop over, like a list) is positional-only. key and reverse are keyword-only, with defaults. So sorted(scores, True) fails: you must write sorted(scores, reverse=True). This shape keeps the most important argument (the data itself) first and unnamed, and makes every option say its name.

Unpacking when calling

def add(a, b):
    return a + b

def tea(kind, *, sugar=0, milk=False):
    return f'{kind} | s={sugar} m={milk}'

nums = [2, 5]
extras = {'sugar': 2, 'milk': True}
# the same as add(2, 5)
print(add(*nums))   # 7
# the same as tea('mint', sugar=2, milk=True)
print(tea('mint', **extras))  # mint | s=2 m=True

Your turn

0 of 3 solved

Exercise 1

+35 XP
Define send(message, *, priority='low', encrypted=False), where the bare * makes priority and encrypted keyword-only. It returns f'{message} | p={priority} e={encrypted}'. For example, send('hi') is 'hi | p=low e=False'.
def send(message):
    # add the bare * and the two keyword-only parameters
    pass

Run your code to check it against the tests.

Exercise 2

+35 XP
Define area(width, height, /), where the / makes both parameters positional-only, returning the area of the rectangle. Then define label(text, /, *, upper=False): text is positional-only, upper is keyword-only, and it returns text in capitals when upper is True, or unchanged otherwise.
def area(width, height):
    # make both positional-only
    pass




def label(text, upper=False):
    # text positional-only, upper keyword-only
    pass

Run your code to check it against the tests.

Exercise 3

+35 XP
Define configure(host, *, port=80, tls=False) returning the tuple (host, port, tls). Then call it with unpacking: spread the list positional into the call with * and the dictionary options with **, and store what it returns in result.
def configure(host):
    # port (default 80) and tls (default False) are keyword-only
    pass




positional = ['db.local']
options = {'port': 5432, 'tls': True}
result = None  # call configure, unpacking both

Run your code to check it against the tests.