Default Values as Way to Make a Parameter Optional in Python — and Why Assigning Mutables as Defaults is a Bad Idea.

Pavol Kutaj
2 min readFeb 25, 2021

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
  1. ints
  2. float
  3. string
  4. 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

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com