Default Values as Way to Make a Parameter Optional in Python — and Why Assigning Mutables as Defaults is a Bad Idea.
2 min readFeb 25, 2021
- The aim of this page📝is to cover the capabilities of function arguments in python by defining its three rules, extracting from the Core Python Course: Getting Started | Pluralsight
1. Default argument values come last — and make a parameter optional
- rule: an argument with default values must come after those without default values
- parameters specified in a function definition with
def
are a comma-separated list - they can be made optional by assigning default values to the parameter
- you get a syntax error if you don’t sign function call with all arguments that don’t have an assigned default value
- consider the following one-liner
def printMessage(message="Hello World"): print(message)>>> printMessage()
Hello World
2. Default values only on immutables
- rule: do not use mutable default values; use only immutable default values
- ✅
ints
- ✅
float
- ✅
string
- ✅
tupple
- lots of newcomers to Python are affected by this
- remember that
def
itself is a statement executed at runtime, typically upon module import - i.e. this is dynamic and no matter how many times you call that the function object is created only once with
def
- this can also have other negative consequences when using e.g.
lists
as default values
- the fix is to use immutable
None