Function Arguments

Positional and keyword arguments, default values, and the mutable default that catches everyone once.

Overview

Positional and keyword arguments, default values, and the mutable default that catches everyone once.

In this guide
  1. Positional and keyword
  2. Defaults
  3. The mutable default trap
  4. Keyword-only parameters
  5. Arguments are evaluated at the call
  6. Too many parameters is a design signal
  7. Argument order in the definition
  8. What the signature communicates
  9. Passing arguments through
  10. Mutable arguments, not just mutable defaults
  11. Watching the default accumulate
  12. How a call is matched to a signature
  13. Saying what a parameter expects
  14. Choosing the default
  15. Questions people ask about Function Arguments
  16. Function Arguments: recap in one screen

arguments.py

arguments.py Python 3
Output

                    

mutable_default.py

mutable_default.py Python 3
Output

                    

Worth knowing

Positional arguments are matched by order; keyword arguments by name.
In a call, every positional argument must come before any keyword one.
Defaults are evaluated once, at definition time - not on each call.
Never default to a list or dict. Default to None and build it inside.

Function Arguments: A Practical Guide

Python matches args to params two ways. By spot and by name. And gives params default values. One of those defaults has a trap in it that each Python programmer meets just once.

Positional and keyword

def greet(name, greeting="Hello"):

greet("ana") matches by position: the first argument fills name. greet("ana", greeting="Hi") names the second explicitly. Both reach the same function. The difference is what the call site tells a reader.

Keywords earn their place when the value alone is meaningless. send(msg, True) tells you nothing about what True controls. send(msg, urgent=True) tells you everything. A boolean argument is almost always worth naming.

One rule: in a call, positional arguments come first. f(greeting="Hi", "ana") is a syntax error. Python cannot tell where the positional one was meant to go once a keyword has appeared.

Understanding how arguments work is one of the first steps toward writing functions that other people can use without reading the source. A good signature communicates what a function needs and what is optional. A poor one forces the caller to memorize positions and guess at meanings.

Python gives you several tools for this. Default values let you make arguments optional. The caller supplies them when needed and skips them when the default is right. This keeps simple calls short while still allowing full control. A function like open(path, mode="r", encoding="utf-8") has one required argument and two optional ones. Most callers pass only the path.

Keyword-only arguments, defined after a bare * in the signature, force the caller to name them. That prevents mistakes where someone passes arguments in the wrong order and gets a silent wrong result. Position-only arguments, marked with /, do the opposite: they forbid naming, so the author can rename them later without breaking callers.

This page covers positional and keyword arguments, defaults and the mutable default trap, keyword-only and position-only parameters, and how these pieces fit together in a clean function signature.

Defaults

A param with a default turns optional:

def greet(name, greeting="Hello", excited=False):

Callers supply what they care about and skip the rest. Defaults must come after all non-default params, for the same reason: or else a spot-based call would be ambiguous.

The mutable default trap

This looks reasonable and isn't:

def add_item(item, basket=[]):
    basket.append(item)
    return basket

Call it three times with no basket and you get one item, then two, then three. All in the same list. The reason is a single rule with a large consequence: default values are tested once, when the def runs, not on each call. That one list is created at meaning time and reused forever, so each mutation builds up.

The second program on this page prints the id of the default object before and after a call, to show it really is the same object rather than a new one that happens to have old contents.

The fix is idiomatic and worth storing:

def add_item(item, basket=None):
    if basket is None:
        basket = []

None is immutable, so there's nothing to build up. The fresh list is built inside the call where it belongs.

Immutable defaults — numbers, strings, True, None, tuples — are all safe. The rule is simply. Never default a param to a list, dict or set.

Keyword-only parameters

any of it after a bare * in the meaning can only be passed by name:

def connect(host, *, timeout=30, retries=3):
    ...

connect("db.local", timeout=5)      # fine
connect("db.local", 5)              # TypeError

This is how you stop a call site from turning a row of untagged values. connect("db.local", 5, 2) tells a reader nothing. Forcing the names makes the call self-documenting, and it means you can reorder or add options later without breaking anyone.

The mirror image is /. This Marks params as spot-based-only. It appears in the standard library more than in use code.

Arguments are evaluated at the call

def log(message, when=now()):    # now() runs ONCE, at definition

This is the same rule as the mutable default, wearing different clothes. If you want the current time on each call, find it inside:

def log(message, when=None):
    if when is None:
        when = now()

Any formula in a default - a function call, a list, a dict, an object - is tested once when the def statement runs, and the result is reused forever.

Too many parameters is a design signal

A function with eight params is hard to call right and hard to change. Two usual remedies:

  • group related args into a small object or a dataclass, so draw(config) replaces draw(x, y, w, h, colour, border, alpha, z)
  • split the function, because eight params often means it's doing more than one job

Neither is a rule, but if you're counting args on your fingers at the call site, the call site is telling you a thing.

Argument order in the definition

Spot-based first, then defaults, then *args, then keyword-only, then **kwargs. Python enforces most of that, and the error messages are clear when you get it wrong - unlike the mutable default. This Never complains at all.

What the signature communicates

A function signature is the part other people read most and change least. It's worth treating as an interface rather than an accident of how the function grew.

Params with no default are needs: the caller must supply them and the function can't work without them. Params with defaults are options, and the default should be the choice that is right most of the time. If you find yourself writing a default that callers nearly always override, the default is wrong and it's quietly making each call site longer.

Order matters for reading as much as for the language. Put the thing the function is about first - the data, the object, the path - and the modifiers after it. resize(image, width=800) reads right. resize(width=800, image=img) is legal and reads backwards.

Passing arguments through

When one function calls another and wants to forward what it was given, the star forms do it without repeating the signature. That is the right tool for wrappers, decorators and thin adapters. Here Repeating the params would mean updating two places each time the inner function changes.

It's the wrong tool for a function people call right. def process(*args, **kwargs) gives the caller no idea what to pass, gives the editor nothing to complete, and turns a mistake that would have been a clear TypeError into a KeyError a place deeper. Be clear at the surface and flexible only where you're truly forwarding.

Mutable arguments, not just mutable defaults

The default-arg trap gets the focus. But The same underlying fact - that args are passed by ref to the same object - applies to each call. A function that appends to a list it was given has changed the caller's list. at times that is the point and should be said in the name: add_item, update_config, sort_in_place. When it isn't the point, copy at the top of the function or return a new object, and let the caller decide.

Watching the default accumulate

The trap is more lifelike when the shared object is visible:

def add_item(item, basket=[]):
    basket.append(item)
    return basket


print(add_item("a"))
print(add_item("b"))
print(add_item("c"))
print("the default itself:", add_item.__defaults__)
['a']
['a', 'b']
['a', 'b', 'c']
the default itself: (['a', 'b', 'c'],)

The last line is the point. __defaults__ holds the actual default values, and the list stored there has grown. It isn't that each call in some way gets the previous result, it's that there has only ever been one list, created when def ran, and each call has been appending to it.

Nothing about this is a special rule for functions. basket=[] is an formula tested once, at meaning time, just like x = [] at module level. The surprise comes from expecting the default to be re-tested on each call, which nothing in the syntax promises.

The fix, once more, because it's worth having in your fingers:

def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

None can't build up any of it, and the list is built inside the call where it belongs.

How a call is matched to a signature

Understanding the binding order makes the error messages readable, and there are only four steps.

Spot-based args are assigned to params left to right. Then keyword args are matched by name to what is left. Then any param still unfilled takes its default. Then, if a param is still unfilled and has no default, the call fails.

That order shows the errors. missing 1 needed spot-based arg: 'x' means step four found a gap. got multiple values for arg 'x' means a spot-based arg filled x in step one and a keyword tried to fill it again in step two — which is what happens when you pass the first arg positionally *and* by name. got an unexpected keyword arg 'timeuot' means step two found no param of that name. This Is the typo case, and is just the error that **kwargs would have swallowed.

Two rules follow from the same sorting. In a call, spot-based args must come before keyword ones, because Python can't tell where a spot-based one belongs once names have started. And in a meaning, params with defaults must come after those without, for the same reason from the other side.

Saying what a parameter expects

Type hints don't convert or enforce any of it at runtime, and they're still the cheapest docs a signature can carry:

def greet(name: str, times: int = 1) -> str:
    return f"hello {name} " * times

The value is threefold. A reader learns what to pass without reading the body. An editor can complete and check the call. And a type checker run in CI catches the mismatch before it ships. Which is the only one of the three that really blocks any of it.

Two rules are worth adopting with them. Annotate the public functions and skip the obvious inner ones. Annotations on a two-line helper cost more to read than they explain. And when a param can be None, say so — def find(name: str) -> User | None. Because that is the case callers most often forget and the one a checker most usefully flags.

Hints also doc the mutable-default fix nicely: basket: list | None = None states both the type and that omitting it's allowed, which is just what the None sentinel means.

Choosing the default

A default is a choice about what most callers want, and getting it wrong is quiet: nothing fails, each call site just gets a little longer.

The test is simple. If most calls override the default, the default is wrong. Either it should be the value people really pass, or the param should be needed so that callers have to think about it. A default that exists only because the param felt like it needed one adds a choice without making one.

Defaults should also be safe rather than convenient. A timeout=None meaning "wait forever" is a default that turns a slow dependency into a hung program; a finite timeout is the better choice though it can fail. The same thinking applies to overwrite=False, strict=True and retries=0: when in doubt, default to the action whose failure is loud.

And a default shouldn't depend on the state of the world. any of it tested at meaning time — the current directory, the time, an environment variable, a config object — is frozen at import and will be wrong for any program that changes it afterwards. None plus a lookup in the body reads the value when the call happens. This Is nearly always what was meant.

Finally, prefer a default over an optional param that changes the return type. A function that returns a number most times and a tuple when verbose=True has two signatures pretending to be one, and each caller has to know which it triggered.

Questions people ask about Function Arguments

Are args passed by value or by ref? Neither, in the C sense. The function gets another name for the same object, so mutating it's visible to the caller and rebinding isn't.

Can a default refer to another param? No. Defaults are tested at meaning time, when no args exist. Use None and find it in the body.

Why must defaults come last? Or else a spot-based call could not tell which param a value was for.

Is a tuple a safe default? Yes. Tuples are immutable, so there is nothing to build up.

How do I force a caller to use names? Put a bare * before those params in the meaning.

Can I see a function's defaults? f.__defaults__ for spot-based ones and f.__kwdefaults__ for keyword-only ones.

How many params is too many? When you're counting on your fingers at the call site. Group them into an object, or split the function.

Can I make each param keyword-only? Yes, put the bare * first: def f(*, a, b). Callers must then name both.

Does the order of keyword args matter? Not to Python. They are matched by name, so any order works. Though matching the signature's order helps a reader.

Can two params share a default object? They can, and they shouldn't if it's mutable, because then both build up into the same thing.

Function Arguments: recap in one screen

  • args match by spot first, then by name. Spot-based ones come first in a call and non-default params come first in a meaning.
  • Defaults are tested once, when def runs. Never default to a list, dict or set.
  • None plus a check in the body is the idiomatic fix, and it reads right in a type hint too.
  • A bare * makes the params after it keyword-only. This Is how a call site stops being a row of untagged values.
  • The signature is the part others read most. Needed params are needs, and a default should be the right choice most of the time.

Check yourself

0 of 3

Answer without scrolling back up.

  1. When is a default argument value evaluated?

  2. What is the fix for `def f(items=[])`?

  3. Which call is a syntax error?

Cheat sheet

Function Arguments

Pass arguments by position or by name, set defaults, and see how Python matches each call to the parameters a function expects.

PYTHON · vizlearn.in/python/function_arguments.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.