1

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?)
3
  • I am not understanding your question. Would naming the variables in your function call do it, e.g., foo(a2_string="XXXXX") or could you use **kwargs to get what you want? Commented Sep 11, 2021 at 7:07
  • if you are passing both arg1 and arg2 anyway, then you don't need the default value because they are used when there are fewer arguments than defined. Just do something like print(arg1 or "default1", arg2 or "default2") Commented Sep 11, 2021 at 7:15
  • Please could you edit the question to show different scenarios (e.g. combinations of value for a1_string and a2_string) and the output you want in each case? Commented Sep 11, 2021 at 11:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Let's say a2_string is not defined. How do I go about printing just foo(a1_string, a2_string) without it giving an error that a2_string is undefined.
what would be the advantage of the or statements assigned? wouldn't they be covered by the default values in the function signature anyways?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.