Pythonic方式在条件上传递关键字参数

atp*_*atp 13 python

是否有更多的pythonic方式来做到这一点?

if authenticate:
    connect(username="foo")
else:
    connect(username="foo", password="bar", otherarg="zed")
Run Code Online (Sandbox Code Playgroud)

jte*_*ace 20

  1. 您可以将它们添加到这样的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 那样重复两次.

  2. 也可以使用这种替代方法,但只有在知道默认参数的情况下才能使用.由于重复的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)

  • 选项 2 有时会带来麻烦,我认为应该避免。在一些带有可选关键字参数(以对象作为参数)的库中,我看到了诸如“if x in kwargs:”之类的东西,后面跟着“print(x.info)”。如果“x == None”,这会引发异常,因为它没有属性“.info” (2认同)

Han*_*nes 7

在这种情况下,与条件参数的数量相比,无条件参数的数量较少,OP 的版本实际上是可以的。这是因为只有无条件参数必须在 if-else 结构的两个分支中重复。但是,我经常遇到相反的情况,即与条件参数相比,无条件参数的数量很高。

这是我使用的:

connect( username="foo", 
         **( dict( password="bar", otherarg="zed") if authenticate else {} ) )
Run Code Online (Sandbox Code Playgroud)