Getting Caught with Sticky Default Arguments

Intuitive Python — by David Muller (33 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Handling Datetimes with Timezones | TOC | Wrapping Up 👉

Python allows you to specify arguments with defaults in your function signatures. For example, consider the use_exclamation argument in the print_greeting function:

​ ​def​ ​print_greeting​(name, use_exclamation=False):
​ greeting = ​"Hello "​ + name
​ ​if​ use_exclamation:
​ greeting += ​"!"​
​ ​print​(greeting)

In the above example, the use_exclamation argument to the print_greeting function has a default value of False. Since use_exclamation defaults to False, print_greeting(“David”) outputs Hello David (with no trailing ! character). If we provided a value for the use_exclamation argument, however, the output changes. print_greeting(“David”, use_exclamation=True) outputs Hello David! because the value for use_exclamation is now True instead of its default value of False.

Default arguments are quite useful, and you’ll see them appear in almost any Python code you encounter. In the standard library, for example, the sorted built-in function includes a reverse argument that defaults to False. The reverse argument allows the following useful modulation:

  • sorted([3, 1, 2]) returns [1, 2, 3]
  • sorted([3, 1, 2], reverse=True) returns [3, 2, 1]

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.