有条件地将任意数量的默认命名参数传递给函数 [英] Conditionally passing arbitrary number of default named arguments to a function
本文介绍了有条件地将任意数量的默认命名参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以有条件地将任意数量的命名默认参数传递给Python函数?
例如,有一个函数:
def func(arg,arg2 ='',arg3 ='def')
code>
现在逻辑是我有一个条件来确定是否需要传递arg3,我可以这样做:
if condition == True:
func('arg',arg2 ='arg2',arg3 ='some value')
else:
func('arg',arg2 ='arg2')
问题是,我可以使用简写吗?
func('arg','arg2','some value'if条件== True else#没有任何东西,所以默认获取
)
解决方案 div>
我能想到的唯一方法是
$ $ $ $ $ $ c $ func(arg,arg2,** ({arg3:some value} if condition == True else {}))
或
func(arg,arg2,*((some value,)if condition == True else ()))
但请d不要这样做。使用你自己提供的代码或者类似的东西:
if条件:
arg3 =some value,
else:
arg3 =()
func(arg,arg2,* arg3)
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
)
解决方案
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)
这篇关于有条件地将任意数量的默认命名参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文