I am trying to write code that does not repeat itself, following the DRY principle.
Consider a function call with many arguments, both mandatory and optional. In some cases, I would like to specify a value for an optional argument, whereas in other cases I would like to leave that value to its default value. To simplify my problem:
def func(a, b=2):
print("b = {}".format(b))
avalue = 1
condition = 2
arg = None # <-- Means: "use default"
if condition == 1:
arg = 3
func(avalue, b=arg)
Output:
b = None
Expected output:
b = 2
Thus, I am trying to avoid coding the function call twice like this:
if arg:
func(avalue, b=arg)
else:
func(avalue)
Is it possible in Python?
Use a dictionary, and only set the optional argument as a key-value pair in that if you want to specify it. Then apply the dictionary using the **kwargs
call syntax:
avalue = 1
condition = 2
kwargs = {}
if condition == 1:
kwargs['b'] = 3
func(avalue, **kwargs)
An empty dictionary (the condition != 1
case) leaves b
set to the default value.