Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 149 ยท Functions

Arguments: Defaults, *args and **kwargs

Master Python function arguments. Use positional and keyword arguments, default values, *args and **kwargs, keyword-only and positional-only parameters safely.

In Functions every parameter was required: call the function with too few arguments and Python raises a TypeError. Real functions need more flexibility. A print() call can take one value or twenty. sorted() works fine without a key, but accepts one when you need it. And some arguments are clearer when the caller is forced to name them.

Python gives you precise control over all of this. In this lesson you'll learn the difference between positional and keyword arguments, how to give parameters default values (and avoid the most famous trap in Python), how to accept any number of arguments with *args and **kwargs, and how to mark parameters as keyword-only or positional-only.

Positional and keyword arguments

When you call a function, you can pass each argument in one of two ways:

  • Positionally: matched to parameters by order.
  • By keyword: name=value, matched by parameter name, in any order.
Python Two ways to pass arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can mix the two styles, with one rule: positional arguments must come before keyword arguments. This call breaks it:

Python
book_flight(origin="NBO", "AMS", 2)
# SyntaxError: positional argument follows keyword argument

Python checks this rule while reading your code, before anything runs, so not a single line of the file executes. Paste that line into the editor above to see the error for yourself.

Keyword arguments make calls self-documenting. Compare resize(800, 600, True) with resize(800, 600, keep_ratio=True). The second one tells you what True means without looking anything up.

Default values

Give a parameter a default with = in the definition. Callers can then leave that argument out:

Python Default parameter values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Parameters with defaults must come after parameters without them, so def greet(greeting="Hello", name): is a SyntaxError. With keyword arguments, callers can skip any defaults they don't care about, as make_tea(size="large") shows.

The mutable default trap

Default values are evaluated once, when the def statement runs, not each time the function is called. For immutable values like numbers, strings and None, that never matters. For a mutable value such as a list or dictionary, every call shares the same object:

Python The shared list bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fix is a standard Python idiom: use None as the default, and create the new list inside the function. Checking is None (rather than if not basket) matters, because a caller might deliberately pass an empty list they want filled.

Warning: Never use [], {}, set() or any other mutable object as a default value. Use None and create the object inside the function. Linters flag this mistake for a reason.

*args: any number of positional arguments

Put a * before a parameter name and it collects all extra positional arguments into a tuple. By convention it's called args, but any name works:

Python Collecting with *args

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is the same star you met in Unpacking and Star Expressions, working in the opposite direction. In a definition, *numbers collects arguments into a tuple. In a call, *values spreads a list into separate arguments.

**kwargs: any number of keyword arguments

Two stars before a parameter collect all extra keyword arguments into a dictionary. The conventional name is kwargs (keyword arguments):

Python Collecting with **kwargs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

**kwargs is useful for functions that pass options through to something else, or that accept open-ended settings. Use it with care, though: explicit parameters show up in editor hints and error messages, while **kwargs hides what a function really accepts.

Keyword-only parameters

Any parameter that comes after *args, or after a bare *, can only be passed by keyword. That's a great tool for flags and options that would be confusing as plain positional values:

Python Keyword-only parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The bare * collects nothing; it just marks the boundary. Now nobody can write the mysterious resize(800, 600, False, 70). They must write keep_ratio=False, quality=70, which reads clearly. In join_words, sep comes after *words, so it's automatically keyword-only. That's exactly how print()'s own sep and end work.

Positional-only parameters

The opposite marker is /. Parameters before a / can only be passed positionally:

Python
def distance(x1, y1, x2, y2, /):
    return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5

distance(0, 0, 3, 4)          # 5.0
distance(x1=0, y1=0, x2=3, y2=4)   # TypeError

Why would you want that? Positional-only parameters let you rename them later without breaking anyone's code, and they keep names that mean nothing to callers out of the public interface. Many built-ins already work this way: len(obj=[1, 2]) fails because len()'s parameter is positional-only.

Putting it all together

A function can use every kind of parameter at once. The order is fixed:

Python
def f(pos_only, /, normal, *args, kw_only, **kwargs):
    ...
  1. positional-only parameters, then /
  2. normal parameters (positional or keyword)
  3. *args (or a bare *)
  4. keyword-only parameters
  5. **kwargs
Python Every kind of parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You'll rarely need all five kinds in one function. Most everyday functions use normal parameters with a few defaults, plus keyword-only options when a boolean or setting would be unclear. Reach for *args and **kwargs when you genuinely need flexibility, such as in decorators that wrap other functions.

Tip: When a call has more than two or three arguments, or any argument is a bare True, False or None, pass it by keyword. Your future self will thank you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given def greet(name, greeting="Hi"):, which call is invalid?

    A positional argument can't follow a keyword argument, so Python reports a SyntaxError.
  2. 2. What's wrong with def add(item, items=[]):?

    Defaults are evaluated once, when def runs. Use items=None and create a new list inside the function.
  3. 3. Inside def f(*args, **kwargs):, what types are args and kwargs?

    Extra positional arguments are collected into a tuple, extra keyword arguments into a dictionary.
  4. 4. With def save(path, *, overwrite=False):, how must overwrite be passed?

    Parameters after a bare * are keyword-only, so save("a.txt", True) raises TypeError.

Summary

  • Arguments are passed positionally (by order) or by keyword (name=value); positional ones must come first.
  • Default values make parameters optional; parameters with defaults follow those without.
  • Defaults are evaluated once, so never use a mutable default: use None and create the object inside.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • Parameters after * or *args are keyword-only; parameters before / are positional-only.
  • The full order is: positional-only, /, normal, *args or *, keyword-only, **kwargs.

Next: Return Values, where you'll return results, several values at once and exit functions early.