Module lessons (2/4)
Default and keyword arguments
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 theNonesentinel.
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
- 1The mental model: the default arises once a week
def - 2Positional arguments vs keyword arguments
- 3The mutable default bug and its fix with
None - 4Quick check
- 5Test yourself
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.