Defining a function with optional arguments

Download python eBook

Example

Optional arguments can be defined by assigning (using =) a default value to the argument-name:

def make(action='nothing'):
    return action

Calling this function is possible in 3 different ways:

make("fun")
# Out: fun

make(action="sleep")
# Out: sleep

# The argument is optional so the function will use the default value if the argument is 
# not passed in.
make()   
# Out: nothing

Warning

Mutable types (list, dict, set, etc.) should be treated with care when given as default attribute. Any mutation of the default argument will change it permanently. See Defining a function with optional mutable arguments.

Stats

Contributors: 9
2016-08-09
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook