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, ar
You can write a helper function
def caller(func, *args, **kwargs):
return func(*args, **{k:v for k,v in kwargs.items() if v != caller.DONT_PASS})
caller.DONT_PASS = object()
Use this function to call another function and use caller.DONT_PASS
to specify arguments that you don't want to pass.
caller(func, 'arg', 'arg2', arg3 = 'some value' if condition else caller.DONT_PASS)
Note that this caller()
only support conditionally passing keyword arguments. To support positional arguments, you may need to use module inspect
to inspect the function.
If you have a function that has a lot of default arguments
def lots_of_defaults(arg1 = "foo", arg2 = "bar", arg3 = "baz", arg4 = "blah"):
pass
and you want to pass different values to some of these, based on something else going on in your program, a simple way is to use **
to unpack a dictionary of argument names and values that you constructed based on your program logic.
different_than_defaults = {}
if foobar:
different_than_defaults["arg1"] = "baaaz"
if barblah:
different_than_defaults["arg4"] = "bleck"
lots_of_defaults(**different_than_defaults)
This has the benefit of not clogging up your code at the point of calling your function, if there is a lot of logic determining what goes into your call. You'll need to be carefull if you have any arguments that don't have defaults, to include the values you're passing for those before passing your dictionary.
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
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)