Skip to the solution
MediumBackend9 min read

How do default, keyword-only and positional-only parameters work?

510 views

The problem

Question presented to candidate: "Walk me through this signature: def connect(host, port=5432, /, timeout=10, *, retries=3). What do the slash and the star mean, how are the defaults stored, and why would an API designer choose positional-only or keyword-only parameters?"

What a strong answer should cover:

  • The five parameter kinds: positional-only (before /, Python 3.8+, PEP 570), positional-or-keyword, *args, keyword-only (after * or *args, Python 3.0+, PEP 3102), **kwargs
  • Defaults are evaluated once when def runs and stored on the function (__defaults__, __kwdefaults__); that is why mutable defaults are shared
  • Ordering rules: a parameter without a default cannot follow one with a default among positional parameters, but keyword-only parameters can be required (no default) in any order
  • Why keyword-only: readable call sites for flags and options (retries=3 instead of a mystery 3); why positional-only: the name is not part of the API, so it can be renamed, and the name stays free for **kwargs, matching builtins like len() and divmod()
  • The exact TypeError messages for each misuse, and that inspect.signature / Signature.bind show how Python maps arguments to parameters

Code / implementation expected: Yes β€” write a signature that uses / and *, and show which calls succeed and which raise TypeError.

  • functions
  • parameters

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe slash and the star: which calls work and which raise
PythonWhere defaults live: __defaults__, __kwdefaults__, the code object and inspect

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 83 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

Why use functools.wraps when writing decorators?

Continue