Positional-only parameters and built-in signatures
The / syntax needs Python 3.8 or newer. inspect.signature shows the marks on real built-ins. import inspect loads a toolbox that comes with Python (Topic 6.1 teaches import). The try/except lines catch an error so it can be printed (Topic 7.1).
A bare * in a signature makes every parameter after it keyword-only, and a / makes every parameter before it positional-only (/ arrived in Python 3.8). They let a function's author decide how callers may pass each argument, which keeps APIs readable and flexible to change.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write describe(name, *, age=0, city="unknown") that returns text like Asha, 12, Pune. Show a valid call, and show that passing the age positionally raises TypeError.
Write half(x, /) that returns x / 2. Show that half(x=10) raises TypeError.
Use inspect.signature to print the signatures of round and len. Which of the two lets you pass its first argument by name?
Explain it without notes
What do * and / mean in a parameter list?
Give two reasons to make a parameter positional-only.
Why are boolean flags usually best as keyword-only?
What is the full left-to-right order of parameter kinds in a signature?
Expected output
Hello, Asha!
Hi, Asha!
Hey, Asha!
TypeError: greet() got some positional-only arguments passed as keyword arguments: 'name'
len : (obj, /)
sorted : (iterable, /, *, key=None, reverse=False)
greet : (name, /, greeting='Hello')