0

In this example, I have a function with an optional argument. E.g.

def func_x(arg_foo='foo'):
  # Do something
  pass

While calling the function, I'd like to specify arguments only under certain conditions.

This is one way of doing it.

if cond == True:
  func_x(arg_foo='coo')
else:
  func_x()

However, the real-life example I have (which is actually a boto3 dynamodb query function) has many optional arguments which I'd like to specify under certain conditions.

I'd prefer not to do the following if I have the choice:

if condition_a:
  long_func_call(many_optional_argument_names=many_optional_argument_values)
elif condition_b:
  long_func_call(many_optional_argument_names=many_optional_argument_values)
elif condition_c:
  long_func_call(many_optional_argument_names=many_optional_argument_values)
else:
  long_func_call(many_optional_argument_names=many_optional_argument_values)

I've tried the following but it didn't work:

long_func_call(
  arg1='' if cond_a else 'value',
  arg2=None if cond_b else 'value'
)

The function I'm calling doesn't accept '' nor None as inputs to its optional arguments.

Is there a way I can specify optional arguments given certain conditions?

2 Answers 2

4
kwargs = {}
if condition_a:
    kwargs['arg_a'] = value_a
if condition_b:
    kwargs['arg_b'] = value_b
...
long_func_call(**kwargs)

Use a dict of keyword arguments.

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

Comments

0

You could use a lambda

if cond:
  func = lambda:func_x(arg_foo='coo')
else:
  func = func_x
func()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.