Home > Articles

This chapter is from the book

This chapter is from the book

5.2 Default Arguments

You can attach default values to function parameters by assigning values in the function definition. For example:

def split(line, delimiter=','):
    statements

When a function defines a parameter with a default value, that parameter and all the parameters that follow it are optional. It is not possible to specify a parameter with no default value after any parameter with a default value.

Default parameter values are evaluated once when the function is first defined, not each time the function is called. This often leads to surprising behavior if mutable objects are used as a default:

def func(x, items=[]):
    items.append(x)
    return items

func(1)       # returns [1]
func(2)       # returns [1, 2]
func(3)       # returns [1, 2, 3]

Notice how the default argument retains the modifications made from previous invocations. To prevent this, it is better to use None and add a check as follows:

def func(x, items=None):
     if items is None:
         items = []
     items.append(x)
     return items

As a general practice, to avoid such surprises, only use immutable objects for default argument values—numbers, strings, Booleans, None, and so on.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.