How to Use Default Values for Functions in Python

  • 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

63 Followers

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com