是否有更多的pythonic方式来做到这一点?
if authenticate:
connect(username="foo")
else:
connect(username="foo", password="bar", otherarg="zed")
Run Code Online (Sandbox Code Playgroud)
jte*_*ace 20
您可以将它们添加到这样的kwargs列表中:
connect_kwargs = dict(username="foo")
if authenticate:
connect_kwargs['password'] = "bar"
connect_kwargs['otherarg'] = "zed"
connect(**connect_kwargs)
Run Code Online (Sandbox Code Playgroud)
当您有一组可以传递给函数的复杂选项时,这有时会很有用.在这个简单的例子中,我认为你拥有的更好,但这可以被认为是更加pythonic,因为它username="foo"不像OP 那样重复两次.
也可以使用这种替代方法,但只有在知道默认参数的情况下才能使用.由于重复的if条款,我也不会认为它是非常"pythonic" .
password = "bar" if authenticate else None
otherarg = "zed" if authenticate else None
connect(username="foo", password=password, otherarg=otherarg)
Run Code Online (Sandbox Code Playgroud)在这种情况下,与条件参数的数量相比,无条件参数的数量较少,OP 的版本实际上是可以的。这是因为只有无条件参数必须在 if-else 结构的两个分支中重复。但是,我经常遇到相反的情况,即与条件参数相比,无条件参数的数量很高。
这是我使用的:
connect( username="foo",
**( dict( password="bar", otherarg="zed") if authenticate else {} ) )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2285 次 |
| 最近记录: |