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=Truetea('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