Python: Function Keyword Parameters, Default Values
Keyword parameters
in function definition, a parameter can have this form:
name = default
it's called keyword parameter.
Keyword parameters must come after positional parameters, if any. For example:
def ff(x, y=1, z=2):→ keyword parameter after positional parameter.def ff(y=1, z=2):→ all keyword parameters.
Keyword Parameters means the arguments is optional. In a function call, if keyword parameter didn't get filled, default values are used.
# function with keyword parameters. def ff(x, y=1, z=2): return [x, y, z] print(ff(3)) # [3, 1, 2] print(ff(3, 4)) # [3, 4, 2] print(ff(3, 4, 5)) # [3, 4, 5]
Positional arguments can fill keyword parameters
in function call, positional syntax can also fill keyword parameters.
# function with only keyword parameters. def ff(x=1, y=2): return [x, y] # using positional syntax to fill keyword parameters. print(ff(3)) # [3, 2] print(ff(3, 4)) # [3, 4]
Example. using keyword arguments to fill keyword parameters
# function with only keyword parameters. def ff(x=1, y=2): return [x, y] print(ff(y=3)) # [1, 3] print(ff(y=3, x=4)) # [4, 3]
Warning: when default value is a mutable object
🛑 warning: when default value is a mutable object such as list or dict, the parameter variable's value is whatever the last function call sets it, because default is evaluated once, not on each function call.
def f(xx, yy=[]): yy.append(xx) return yy print(f(1) == [1]) print(f(1) == [1, 1]) # unexpected!!!!!!!!!!!!!!!!
Solution
make the default to be None, then, in the code, check if it is None, assign the default value you want.
def f(xx, yy=None): if yy is None: yy = [] yy.append(xx) return yy print(f(1) == [1]) print(f(1) == [1])
Summary
- in function definition, keyword parameter comes after positional parameters.
- in function call, keyword argument comes after positional arguments.
positional arguments fill the parameters by the order they are given, after that, keyword arguments fill the remaining parameters by matching positional parameter names.