Python Language Functions Defining a function with optional arguments

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Python Language Question?