Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.4 — Keyword-Only and Positional-Only Parameters
Python · Example 2 of 2 Python 3.8+

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.

01

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.

02

Write half(x, /) that returns x / 2. Show that half(x=10) raises TypeError.

03

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

01

What do * and / mean in a parameter list?

02

Give two reasons to make a parameter positional-only.

03

Why are boolean flags usually best as keyword-only?

04

What is the full left-to-right order of parameter kinds in a signature?

Positional-only parameters and built-in signatures Python 3.8+
Sign in to run this example in your browser.

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')