Python/Tutorial/Functions/Defining a Function with Default Parameters

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Introduction

Sometimes, you can write a function that doesn't need all of the parameters specified to be called. This function would know a good default to use ahead of time.

Syntax

In the function definition, you specify a default value for a parameter by adding '=' and then an expression. This will set the default to the value of that expression.

The default parameters must be last. That is, you can't specify a non-default parameter after a default parameter.

Meaning

When the function is called, the default parameter may or may not be specified. If it is specified, then the specified value is used. If not, then the default value is used.

Caveat

When writing a function with default parameters, keep in mind that the default parameter survives after each function call. If you use a mutable value, then keep in mind the next time the function is called, the value will be the latest value of that mutable value.

Example:

def func(the_list=[]):
    the_list.append(5)
    return the_list

Each time you call func, if you don't specify the_list, it will append 5 to the default value for the_list. This means over time, it will grow.

This may be what you want, but the actual cases where this are useful are very limited in Python. It has more to do with scoping than anything else.

Examples

In Practice

Homework