Håkon Hægland
Håkon Hægland

Reputation: 40778

How to indicate that a function should use its default value of an optional argument without omitting it?

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?

Upvotes: 2

Views: 116

Answers (5)

Tomos Williams
Tomos Williams

Reputation: 2088

Op has mentioned that the function func can't be modified so my sugguestion would be :

def func(a, b=2):
    print("b = {}".format(b))

avalue = 1
condition = 2
if condition == 1:
    func(avalue, b=3)
else:
    func(avalue)

Upvotes: 0

be_good_do_good
be_good_do_good

Reputation: 4441

One of the solutions can be:

def func(a, b=2, **kwargs):
    print("b = {}".format(b))

avalue = 1
condition = 2

func(avalue, **{} if condition != 1 else {'b':3})

Upvotes: 1

Ma0
Ma0

Reputation: 15204

How about this:

def func(a, b=None):
    b = 2 if not b else b
    print("b = {}".format(b))

avalue = 1
condition = 2
arg = None  # <-- Means: "use default"
if condition == 1:
    arg = 3

func(avalue, arg)  # b = 2

and if condition = 1:

func(avalue, arg)  #  b = 3

The above assumes you can modify the function definition. If that is not the case you have to go with **kwargs.

Upvotes: 0

Tomos Williams
Tomos Williams

Reputation: 2088

What about :

def func(a, b=None):
    if not b:
        b = 2
    print("b = {}".format(b))

avalue = 1
condition = 2
arg = None  # <-- Means: "use default" 
if condition == 1:
    arg = 3

func(avalue, b=arg)

At this point however the default isn't really used the way it should be, defaults are usually kept for when you have two different methods, one that works in a way that the other shouldn't for example for addition/subtraction with a switch:

def maths(a,b,sub=false):
    result = a + b
    if sub:
        result = a - b
    return result

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125078

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.

Upvotes: 4

Related Questions