Flyn Sequeira
Flyn Sequeira

Reputation: 690

How to conditionally add arguments of optional parameters in python?

If I have a function defined with default values, and I want to use them conditionally Eg. In the function below -

def foo(arg1='some_default_string1', arg2='some_default_string1'):
    print(arg1,arg2)

If I had to call the function with a1_string/a2_string either having values or not.

if a1_string and not a2_string:
    foo(a1_string)
elif not a1_string and a2_string
    foo(a2_string)
elif a1_string and a2_string:
    foo(a1_string, a2_string)
else:
    foo()

could this be done in a single line such as

foo(a1_string?, a2_string?)

Upvotes: 1

Views: 616

Answers (1)

U13-Forward
U13-Forward

Reputation: 71580

You could use the or operator:

def foo(arg1='some_default_string1', arg2='some_default_string2'):
    arg1 = arg1 or 'some_default_string1'
    arg2 = arg2 or 'some_default_string2'
    print(arg1, arg2)

This would work for all cases.

Upvotes: 1

Related Questions