Skip to main content
Module 5 · Lesson 2 of 418/36 in the course~16 min
Module lessons (2/4)

Default and keyword arguments

Lesson preview5 hands-on exercises readyPython Course · Module 5 — Functions

Default parameter values, keyword calls, positional-before-keyword rules, and the mutable default pitfall.

What you'll learn in this lesson

  • Simplify signatures with default parameters and explicit calls via keyword arguments.
  • Respect the syntactic rules of order between positional arguments, keyword arguments and separator (/, *).
  • Avoid the mutable default pitfall (box=[]) forever by using the None sentinel.

Overview

Default parameters and keyword arguments make the Python API readable as prose. However, there is a trap famous throughout the Python world linked to the life cycle of the memory: the default values are evaluated only once at the moment of definition def, not at every call!

When Python reads def add_tag(tag, box=[]):, it allocates a single list [] in memory and hooks it to the function object add_tag.__defaults__. If a call appends an element to box, all future calls without a second argument will share that same already dirty list!

Sections covered in this lesson

  1. 1The mental model: the default arises once a week def
  2. 2Positional arguments vs keyword arguments
  3. 3The mutable default bug and its fix with None
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 5 — Functions

Unlock "Default and keyword arguments" and the full Python Course curriculum

Default parameter values, keyword calls, positional-before-keyword rules, and the mutable default pitfall.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.