Skip to the solution
EasyDSA10 min read

What do *args and **kwargs mean?

743 views

The problem

Question presented to candidate: "You see def handler(*args, **kwargs) all over a codebase. What do the single and double star actually do, what types do args and kwargs end up as, and how is that different from putting a star in front of something when you call a function?"

What a strong answer should cover:

  • In a definition, *args collects any extra positional arguments into a tuple and **kwargs collects any extra keyword arguments into a dict; the names are convention, the stars are the syntax
  • At a call site the stars do the reverse: f(*seq) spreads an iterable into positional arguments and f(**mapping) spreads a mapping into keyword arguments (string keys only)
  • Parameter order: regular parameters, then *args, then keyword-only parameters, then **kwargs; anything after *args can only be passed by keyword
  • The forwarding pattern def wrapper(*args, **kwargs): return func(*args, **kwargs) used by decorators, and the cost: a vaguer signature for callers and type checkers
  • Details: each call gets a fresh tuple and dict, kwargs keeps the caller order (guaranteed since Python 3.6, PEP 468), and filling the same parameter twice raises TypeError

Code / implementation expected: Optional β€” a few lines showing packing in a def and unpacking in a call, ideally a small forwarding wrapper.

  • args
  • kwargs

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

10 min read Β· 11 sections

Run the code

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

PythonPacking: what *args and **kwargs receive
PythonUnpacking at the call site, forwarding and the TypeError gotchas

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 13 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 nextEasy

How are Python dictionaries implemented and ordered?

Continue