How to Use Default Values for Functions in Python

The aim of this page📝is to list 2 best practices for using default values in Python functions

Pavol Kutaj
1 min readSep 14, 2022
  • consider the following one-liner illustrating the syntax of default value assignment
def printMessage(message="Hello World"): print(message)>>> printMessage()
Hello World

1. DEFAULT VALUES COME LAST

  • rule: in a function definition, parameters with default values must come after those without default values
  • parameters specified in a function definition with def are a comma-separated list
  • as you may know, function parameters they can be made optional by assigning a default values to the parameter as illustrated in the example above
  • …and you get a syntax error if you don’t sign function call with all arguments that don’t have an assigned default value

2. DEFAULT VALUES SHOULD BE USED ONLY ON IMMUTABLE TYPES

  • rule: do not use mutable default values; use only immutable default values
  • the default value for an argument is only evaluated once, at the time the enclosing def statement is executed
  • the enclosing def statement is typically executed upon `import`
  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 (there is no hoisting)
  • 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-only for default function values

--

--

No responses yet