Alex Rivera | Logout

Conditionally passing arbitrary number of default named arguments to a function

Asked 2011-01-12T15:39:52.193
13

Is it possible to pass arbitrary number of named default arguments to a Python function conditionally ?

For eg. there's a function:

def func(arg, arg2='', arg3='def')

Now logic is that I have a condition which determines if arg3 needs to be passed, I can do it like this:

if condition == True:
    func('arg', arg2='arg2', arg3='some value')
else:
    func('arg', arg2='arg2')

Question is, can I have a shorthand like:

func('arg', 'arg2', 'some value' if condition == True else # nothing so default gets picked
)
Edit
Report

2 Answers

10

The only way I can think of would be

func("arg", "arg2", **({"arg3": "some value"} if condition == True else {}))

or

func("arg", "arg2", *(("some value",) if condition == True else ()))

but please don't do this. Use the code you provided yourself, or something like this:

if condition:
   arg3 = "some value",
else:
   arg3 = ()
func("arg", "arg2", *arg3)
answered 2011-01-12T15:42:51.143
9

That wouldn't be valid Python syntax you have to have something after else. What is done normally is:

func('arg', 'arg2', 'some value' if condition else None)

and function definition is changed accordingly:

def func(arg, arg2='', arg3=None):
    arg3 = 'def' if arg3 is None else arg3
answered 2011-01-12T15:44:16.487

Your Answer