Conditionally passing arbitrary number of default named arguments to a function

旧时模样 提交于 2019-11-29 09:47:43

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)

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!