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?

kev
  • 1,085
  • 2
  • 10
  • 27

2 Answers2

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

You could use a lambda

if cond:
  func = lambda:func_x(arg_foo='coo')
else:
  func = func_x
func()
TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19