Skip to content
Streak:0Loading your progress…Sign in

Module 1 · Lesson 3 of 3

Functions

Defaults, keyword arguments, *args/**kwargs and the mutable-default trap. ~20 min

Lesson notes

Coming from Dart

Dart

String tag(String text, {String level = 'info'}) => '[$level] $text';
tag('hi', level: 'warn');

Python

def tag(text: str, level: str = "info") -> str:
    return f"[{level}] {text}"

tag("hi", level="warn")

Any parameter can be passed by keyword. Put * in the signature to force keyword-only args: def f(a, *, strict=False).

Variadic arguments
def log(message, *args, **kwargs):
    # args is a tuple, kwargs is a dict
    print(message, args, kwargs)

log("hi", 1, 2, user="ada")   # hi (1, 2) {'user': 'ada'}

Practice

  1. 1. Fix the mutable default

    medium25 XP

    add_tag(tag, tags=[]) should return a list with tag appended. It currently leaks state between calls. Fix it so each call without tags starts fresh, and calls that pass tags don't mutate the caller's list.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. Build a query string

    medium25 XP

    Write build_query(base, **params) that returns base plus ?key=value&... with keys sorted alphabetically. Skip params whose value is None. If nothing remains, return base unchanged.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor