通过Pythonic方法在条件上传递关键字参数

通过Pythonic方法在条件上传递关键字参数,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

有没有更像蟒蛇的方法

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)
    
    当您有一组复杂的选项可以传递给函数时,这有时会很有帮助。在这个简单的例子中,我认为您所拥有的更好,但这可以被认为更像python,因为它不像OP那样重复两次
    username=“foo”

  • 也可以使用这种替代方法,尽管它只在您知道默认参数是什么的情况下起作用。我也不认为它是非常“Pythic”,因为重复的<代码>如果子句。< /P>
    password = "bar" if authenticate else None
    otherarg = "zed" if authenticate else None
    connect(username="foo", password=password, otherarg=otherarg)
    
  • 或者,更简洁地说:

    connect(**(
        {'username': 'foo', 'password': 'bar', 'otherarg': 'zed'}
        if authenticate else {'username': 'foo'}
    ))
    

    我只是想把我的帽子扔进拳击场:

    authenticate_kwargs = {'password': "bar", 'otherarg': "zed"} if authenticate else {}
    connect(username="foo", **authenticate_kwargs)
    

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

    这就是我使用的:

    connect( username="foo", 
             **( dict( password="bar", otherarg="zed") if authenticate else {} ) )
    

    它是一个单一的表达式,可以避免重复引用临时表达式来累积要传递的参数。我的意思是关于原始表达式。这和OP完全一样,只是重新安排了一下;但当我写“或者更简洁地说”时,我的意思并不是指对原文的尊重(而是对另一个答案的尊重)在我看来,除了不够简洁之外,它还增加了歧义。显然,代码并不像上面那样清晰。它怎么会不像Pythonic那么简单呢?条件表达式是完全可以理解的。它读起来像英语一样,按照同样的语序,如下所示:“如果要求验证,则使用结果dict中的关键字连接:”。您所拥有的有什么问题?“不要重复你自己”是一条很好的规则,但如果它使你的代码变得更复杂,就不会那么复杂了,因此,在这种情况下,我看重的是复杂度。选项1比原来的问题更多,更直截了当=/如果你只需要根据其他事物的值设置一个值,那么选项2是完美的。这是我在某种程度上所期望的,但看起来有点丑陋。这是我将使用的。