Python 3D Academyবাংলা

Keyword-only and positional-only parameters

🌍 In real life. A bank transfer form has boxes labelled "From" and "To". If it only had two blank boxes, it would be far too easy to swap them and send the money the wrong way. Labels make mistakes like that impossible.

Python can insist on labels too. The idea in one sentence: a bare * in a function's parameters means every parameter after it must be given by name, and a / means every parameter before it must be given by position.

Its words:

  • keyword-only parameter: one after a bare * (or after *args); it can only be passed as name=value
  • positional-only parameter: one before a /; it can only be passed by position, never as name=value
  • the bare *: a marker, not a parameter: it collects nothing

Step by step, for def transfer(amount, *, sender, receiver):

  1. amount comes before the *, so it can be given by position
  2. sender and receiver come after it, so they must be named
  3. transfer(100, sender="Ana", receiver="Bo") works; transfer(100, "Ana", "Bo") is refused

Watch the named values find their places:

And without the names: after amount, there is no room left for values given by position, so Python stops before the function even starts.

Why it helps. A keyword-only parameter makes the call explain itself: sorted(scores, reverse=True) says what True means; sorted(scores, True) wouldn't, and Python refuses it. It also lets you add more parameters later without breaking calls that already exist. Python's own functions use it everywhere: sorted(items, key=len) (Lesson 16.2) and print(*words, sep=", ") only accept key and sep by name.

A / does the opposite: the names before it are private details, so the function can rename them later. len(obj) is like that: len(obj="abc") is a TypeError. Both markers can appear together:

def describe(name, /, age, *, city="Dhaka"):
    return name + " is " + str(age) + ", from " + city

print(describe("Rimi", 12))
print(describe("Rimi", age=12, city="Sylhet"))
# describe(name="Rimi", age=12)   would stop with a TypeError: name is positional-only
# describe("Rimi", 12, "Sylhet")  would stop with a TypeError: city is keyword-only

Mistakes and edge cases.

  • a * at the very end: def f(a, *): is a SyntaxError, because a bare * must be followed by at least one named parameter
  • * together with *args: a function can't have both; with *args, every parameter after it is already keyword-only
  • the order is fixed: positional-only, then /, then normal ones, then *, then keyword-only, then **kwargs
  • defaults still work: a keyword-only parameter may have a default (city="Dhaka"), and then it can be left out; without one, leaving it out is a TypeError about a missing keyword-only argument

Quiz

  1. What does this print?

    def area(w, h, *, unit="cm"):
        return str(w * h) + " " + unit
    
    print(area(3, 4))
    print(area(3, 4, unit="m"))
  2. With def send(msg, *, to), which call works?

    • send("hi", to="Bo")
    • send("hi", "Bo")
    • send("hi")
  3. With def half(n, /):, which call works?

    • half(10)
    • half(n=10)
    • both of them
  4. What does this print?

    print("a", "b", "c", sep="-")
  5. This won't even run: Python reports a SyntaxError. Which line is wrong?

    def greet(name, *):
        return "Hi " + name
    
    print(greet("Ana"))

Coding tasks

  1. Write transfer(amount, *, sender, receiver) that returns "<sender> sends <amount> to <receiver>", with sender and receiver keyword-only, so a call that gives them by position stops with a TypeError.

  2. Write clamp(value, /, low=0, high=100): return value, but no smaller than low and no bigger than high. value must be positional-only.