如果不是None,则传递**kwargs。

7

我试图将**kwargs传递给另一个函数,但仅在其不为空时传递。目前我有这个if else,我想知道是否有更有效、更符合Python风格的方法?

 if other:
     html.append(self.render_option(val, label, selected, **other))
 else:
     html.append(self.render_option(val, label, selected))

如果 other 是 NoneType,我会收到错误提示:
...argument after ** must be a mapping, not NoneType

1
你为什么担心这个呢?直接跳过它们就好了;如果没有错误,你也不会得到错误提示,对吧? - Jonathan Leffler
我不确定如何让这段代码更短、更简洁、更符合 Python 风格。我可能会显式地进行测试(使用 if other is not None 而不是 if other),但这只是为了语法上的优雅,肯定不会影响执行。 - Adam Smith
@JonathanLeffler 如果other是None,我会得到一个错误argument after ** must be a mapping, not NoneType - Johnston
2个回答

13

我会使用其中任何一个。

html.append(self.render_option(val, label, selected, **(other or {})))
或者
html.append(self.render_option(val, label, selected, **(other if other is not None else {})))

或者更加明确的

if other is None:
    other = {}
html.append(self.render_option(val, label, selected, **other))

传递空字典作为kwargs应该与不指定kwargs相同。


3

这实际上是一条评论,但需要进行格式化,并且太大无法放入评论中。

我建议:

你为什么要担心呢?只需通过它们;如果没有错误,那么就不会出现错误,对吧?

回应如下:

如果 other 是 None,那么会出现错误:argument after ** must be a mapping, not NoneType

反例

def print_kwargs(**kwargs):
  for k in kwargs:
    print k, " => ", kwargs[k]

def kwargs_demo(a, **kwargs):
  print a
  print_kwargs(**kwargs)

kwargs_demo(1)
kwargs_demo(99, **{'cat':'dog', 'ice':'cream'})

输出

1
99
ice  =>  cream
cat  =>  dog

重新建立连接?

你正在做的事情和我认为你正在做的事情之间必须存在断开(以及你的问题标题似乎在问什么)。我可以通过下面代码中对 kwargs_mark2() 的调用来生成你看到的错误:

def kwargs_mark2(a):
  print a
  other = None
  print_kwargs(**other)  # Fails with 'must be a mapping, not NoneType'

kwargs_mark2(24)

修复方法很简单(在kwargs_mark3()中有示例):在需要映射时不要创建None对象,而是创建一个空映射。
def kwargs_mark3(a):
  print a
  other = {}
  print_kwargs(**other)

kwargs_mark3(37)

这并不是要进行反驳,而是想提供一个标准回复。我很抱歉。我喜欢不在一开始就创建None的想法,这样更加聪明。我会尝试找出我犯了什么错误。我正在使用Python 2.7的Flask框架,但这应该不会有影响。 - Johnston
1
我会将“riposte”降级为“response”。我并没有生气或非常沮丧(它促使我去改进我的不稳定的Python)。 - Jonathan Leffler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接