在条件条件下传递关键字参数的Python方法
有没有更Python的方式来做到这一点?
if authenticate:
connect(username="foo")
else:
connect(username="foo", password="bar", otherarg="zed")
-
- 您可以将它们添加到类似kwarg的列表中:
connect_kwargs = dict(username="foo")
if authenticate:
connect_kwargs[‘password’] = “bar”
connect_kwargs[‘otherarg’] = “zed”
connect(**connect_kwargs)
当您可以将一组复杂的选项传递给函数时,这有时会很有帮助。在这种简单的情况下,我认为您有更好的选择,但是可以将其视为 更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)
- 您可以将它们添加到类似kwarg的列表中: