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
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.