Conditionally passing arbitrary number of default named arguments to a function

前端 未结 4 1810
情书的邮戳
情书的邮戳 2020-12-18 23:58

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         


        
4条回答
  •  一整个雨季
    2020-12-19 00:32

    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)
    

提交回复
热议问题