Thuta Learning
Python
AdvancedProgrammingBeginner

Functions (In Depth)

PythonLesson 5935 min

What you'll walk away with

  • Control how arguments are passed by putting / and * in a signature
  • Explain how *args and **kwargs collect arguments into a tuple and a dict
  • Recognise the mutable default argument bug and fix it with a None sentinel
  • Pass functions as arguments and write a closure that uses nonlocal
  • Write function signatures with type hints and a docstring

Explain it simply

Explain it simply

Lesson 19 described a function as a recipe card. Now we make the card's instructions stricter: "never name the first ingredient", "always say the amount of salt by name", "add as many vegetables as you like". Rules like these protect the cook from mistakes.

This lesson is about designing signatures: shaping them so callers cannot call them wrongly, accepting any number of arguments, passing a function itself to another function, and creating functions that remember state (closures).

Problem → Why → Solution

The problem: two calls quietly share one cart

A developer writes add_item(item, cart=[]) believing that leaving out cart starts a fresh one. The first customer's ['tea'] looks right, but the second customer's cart also contains tea. Each test passes alone and fails when the tests run together, and in production one customer's data leaks into another's.

cart_bug.py
def add_item(item, cart=[]):     # the list is created ONCE
    cart.append(item)
    return cart

print(add_item("tea"))    # ['tea']
print(add_item("rice"))   # ['tea', 'rice']  <- someone else's tea!
print(add_item.__defaults__)  # (['tea', 'rice'],)

Why does this happen?

Default values are evaluated once, when the def line runs, which is when the function is defined, and they are stored in the function object's __defaults__. They are not created afresh for each call. Immutable defaults such as numbers and strings are harmless, but if you mutate a list, dict or set default, every later call receives that same mutated object. The fix is to default to None and create the new list inside the body.

Core concept: a signature is a set of rules for callers

Two markers can appear in a parameter list. Parameters to the left of / are positional-only and cannot be passed by name (available since Python 3.8). Parameters to the right of * (or of *args) are keyword-only and must be passed by name, such as discount=0.1. Keyword-only parameters remove the guesswork in a call like total(10, 20, 0.1), where 0.1 could be a price or a discount, and positional-only parameters leave you free to rename them later.

*args collects any extra positional arguments into a tuple, and **kwargs collects any extra keyword arguments into a dict. args and kwargs are only conventional names; the * and ** do the work. On the calling side, f(*numbers) spreads a list into positional arguments and f(**options) spreads a dict into keyword arguments. Be aware that **kwargs also silently accepts misspelled options, colour= instead of color=, so named keyword-only parameters are safer in a public API.

Functions in Python are first-class objects: you can store them in variables, pass them as arguments and return them from other functions. sorted(words, key=len) passes the len function itself, not the result of calling len(). If you define a function inside another function and return it, the inner function remembers the outer function's variables; this is called a closure. To reassign such an outer variable, declare it nonlocal, or Python raises UnboundLocalError.

Type hints, as in def total(*prices: float, discount: float = 0.0) -> float, annotate parameter and return types. The Python runtime does not check them; tools such as mypy and your editor use them to warn about wrong calls ahead of time. A docstring, the first string in the body, shows up in help() and __doc__ and explains what the function does and returns. Hints do not replace runtime validation, so data from outside the program must still be checked.

Mental model: which slot each argument lands in
  1. Left of /: by position only
  2. Extra positional -> *args tuple
  3. Right of *: by name only
  4. Extra keywords -> **kwargs dict
  5. Defaults: built once, at def time

The order is always: positional-only, /, normal, *args, keyword-only, **kwargs.

General pattern

python
def name(pos_only: T, /, normal: T, *args: T, kw_only: T = d, **kwargs: T) -> R:
    """One-line summary of what the function returns."""
    ...

def name(items: list[T] | None = None) -> list[T]:
    if items is None:
        items = []          # fresh object on every call

def outer(setting: T) -> Callable[[A], R]:
    def inner(arg: A) -> R:
        return use(setting, arg)   # inner remembers setting
    return inner

The first signature shows all six kinds of parameter in their required order. The second is the None-sentinel pattern that replaces a mutable default, and the third is a closure that returns a function remembering setting.

Example: a report, tags, a counter and options

Four functions each demonstrate one idea from this lesson: make_report uses /, *rows and keyword-only options; add_tag is the safe version of a mutable default; make_counter is a closure with nonlocal; describe takes **kwargs. Finally we see what happens when a positional-only parameter is passed by name.

functions_in_depth.py
from collections.abc import Callable


def make_report(title: str, /, *rows: str, sep: str = "-", width: int = 12) -> str:
    """Return a title, a rule line, then one row per line."""
    return "\n".join([title, sep * width, *rows])


def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
    if tags is None:
        tags = []
    tags.append(tag)
    return tags


def make_counter(start: int = 0) -> Callable[[], int]:
    count = start

    def step() -> int:
        nonlocal count
        count += 1
        return count

    return step


def describe(**options: object) -> str:
    return ", ".join(f"{key}={value}" for key, value in options.items())


print(make_report("Sales", "Mon 120", "Tue 95", sep="=", width=10))
print(add_tag("a"), add_tag("b"))
counter = make_counter(10)
print(counter(), counter(), counter())
print(describe(debug=True, retries=3))
print(make_report.__doc__)

try:
    make_report(title="Sales")
except TypeError as err:
    print("TypeError:", err)

Code breakdown

  1. Line 4def make_report(title: str, /, *rows: str, sep: str = "-", width: int = 12) -> str:

    title sits before /, so it is positional-only. *rows gathers the remaining positional strings into a tuple, and sep and width come after *rows, so they are keyword-only and must be passed as sep="=" and so on.

  2. Lines 9-11 if tags is None:

    The default is None, which is immutable, and each call builds a new list, so add_tag("a") and add_tag("b") return separate ['a'] and ['b']. The bug from the problem section is gone.

  3. Lines 19-22 nonlocal count

    step() is a closure that remembers make_counter's count. Without nonlocal, count += 1 would be treated as a new local variable and raise UnboundLocalError. Each counter() call continues the sequence: 11, 12, 13.

  4. Line 27def describe(**options: object) -> str:

    **options receives debug=True, retries=3 as the dict {'debug': True, 'retries': 3}, preserving the order they were passed in.

  5. Lines 38-41 make_report(title="Sales")

    title is positional-only, so passing it by name raises TypeError, and the message names the exact parameter that was misused.

You should see
Sales
==========
Mon 120
Tue 95
['a'] ['b']
11 12 13
debug=True, retries=3
Return a title, a rule line, then one row per line.
TypeError: make_report() got some positional-only arguments passed as keyword arguments: 'title'
Functions In Depth Visual Guide
Thinking of a function as a reusable code block, shown as a visual flow.

Passing functions around as values

A function name written without parentheses is the function object itself, so you can store it in a variable and call it later. apply_each is a higher-order function: it receives the behaviour to apply as an argument. The key parameter of sorted(), map() and decorators, which later lessons cover in depth, are all built on this idea.

first_class.py
def shout(text: str) -> str:
    return text.upper() + "!"


def whisper(text: str) -> str:
    return text.lower() + "..."


def apply_each(func, items):
    return [func(item) for item in items]


style = shout                 # no parentheses: the function itself
print(style("hi"))            # HI!
print(apply_each(whisper, ["Hello", "BYE"]))
print(sorted(["kiwi", "fig", "banana"], key=len))

In real projects

Where this shows up in real projects

A report generator might be designed as generate_report(rows, *, title, clock, writer). Title and options are keyword-only, so calling code reads clearly and arguments cannot be swapped. clock, a function that returns the current time, and writer, a function that writes output, are injected as arguments, so a test can pass a fixed-time function and a function that collects lines into a list, then check the result exactly without touching files or the real clock.

Python's standard library uses these techniques itself: the key and reverse parameters of sorted() are keyword-only, and many built-ins such as len() are positional-only. Web frameworks store route handler functions in a registry and call them when a request arrives. Wrappers such as logging helpers accept *args, **kwargs and forward them untouched to the original function. In team projects every public function carries type hints and a docstring, so the editor shows usage on hover and mypy catches type mismatches in CI.

Common mistakes

Common mistakes

1. Using a mutable value as a default

def add_item(item, cart=[]) and def register(user, roles={}) share one object across every call. Default to None and write if cart is None: cart = [] in the body. Avoid if not cart:, because it would also replace an empty list that the caller passed on purpose.

2. Hiding options behind **kwargs

def connect(**kwargs) accepts a typo such as connect(tiemout=5) without complaint and silently ignores the timeout. Write known options as keyword-only parameters, def connect(*, timeout=10, retries=3), and the typo becomes a TypeError.

3. Changing a closure variable without nonlocal

Writing count += 1 in an inner function without declaring nonlocal count raises UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. Any assignment makes Python treat that name as local to the inner function.

4. Calling a function where you meant to pass it

sorted(words, key=len()) calls len with no argument and raises TypeError, and apply_each(shout(), items) fails the same way. When passing a function, leave the parentheses off: key=len, apply_each(shout, items).

Best practices

Best practices

  • Put boolean flags and rarely used options after * as keyword-only parameters.
  • Give every public function type hints and a one-line docstring that says what it returns.
  • Pass side effects such as the clock, files or the network in as arguments instead of calling them directly; it makes testing easy.

Mini challenge

Mini challenge: a pricing toolkit

Write a small pricing toolkit of four functions, each using one technique from this lesson. Every function needs type hints and a docstring.

  • total(*prices, discount=0.0) accepts any number of prices; discount is keyword-only; round to 2 decimals
  • make_discount(percent) is a closure that returns a function taking a percentage off one price
  • apply_all(prices, rule) applies the rule function to every price and returns a list
  • add_item(item, cart=None) must not have the mutable default bug
  • Print total.__doc__, and catch the TypeError from calling make_discount() with no argument
pricing.py
from collections.abc import Callable


def total(*prices: float, discount: float = 0.0) -> float:
    """TODO: one-line docstring"""
    # TODO: sum the prices, apply the discount, round to 2 decimals
    ...


def make_discount(percent: float) -> Callable[[float], float]:
    # TODO: define an inner function that discounts one price, then return it
    ...


def apply_all(prices: list[float], rule: Callable[[float], float]) -> list[float]:
    # TODO: return a new list with rule applied to each price
    ...


def add_item(item: str, cart: list[str] | None = None) -> list[str]:
    # TODO: create a fresh list when cart is None, then append
    ...


# TODO: try total(10, 20, 5), the same with discount=0.1, and total(10, 20, 0.1)
# TODO: ten_off = make_discount(10); apply it to [100.0, 59.9]
# TODO: call add_item twice without a cart; print total.__doc__
# TODO: call make_discount() inside try/except TypeError

Expected: 35.0 31.5 30.1 [90.0, 53.91] ['tea'] ['rice'] Sum any number of prices, then take off a fractional discount. TypeError: make_discount() missing 1 required positional argument: 'percent'

Show hint

total(10, 20, 0.1) treats 0.1 as a third price and returns 30.1, which is exactly why discount is keyword-only. The closure only reads percent, so it needs no nonlocal.

Show solution
pricing.py
from collections.abc import Callable


def total(*prices: float, discount: float = 0.0) -> float:
    """Sum any number of prices, then take off a fractional discount."""
    return round(sum(prices) * (1 - discount), 2)


def make_discount(percent: float) -> Callable[[float], float]:
    """Return a function that applies a fixed percentage discount."""
    def apply(price: float) -> float:
        return round(price * (1 - percent / 100), 2)
    return apply


def apply_all(prices: list[float], rule: Callable[[float], float]) -> list[float]:
    """Run one pricing rule on every price."""
    return [rule(price) for price in prices]


def add_item(item: str, cart: list[str] | None = None) -> list[str]:
    """Add an item to a cart, creating a fresh cart when none is given."""
    if cart is None:
        cart = []
    cart.append(item)
    return cart


print(total(10, 20, 5))
print(total(10, 20, 5, discount=0.1))
print(total(10, 20, 0.1))
ten_off = make_discount(10)
print(apply_all([100.0, 59.9], ten_off))
print(add_item("tea"), add_item("rice"))
print(total.__doc__)
try:
    make_discount()
except TypeError as err:
    print("TypeError:", err)

Quick quiz 1 / 3

Given def f(a, /, b, *, c):, which call is valid?

Quick quiz 2 / 3

With def log(*args, **kwargs): print(args, kwargs), what does log(1, 2, level="info") print?

Quick quiz 3 / 3

Given def add(x, items=[]): items.append(x); return items, what does add(1); print(add(2)) print?

What to remember

  • Parameters before / are positional-only; parameters after * are keyword-only.
  • *args gathers extra arguments into a tuple and **kwargs into a dict; * and ** spread them at the call site.
  • Defaults are evaluated once at def time, so use a None sentinel instead of a mutable default.
  • Functions are values you can pass and return, and a closure remembers outer variables (nonlocal to reassign them).
  • Type hints and docstrings guide tools and people but do not replace runtime validation.

Python Documentation — Functional Programming HOWTO — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Functions (In Depth) | Thuta Learning