我有这样一个函数:
def func(foo, bar, nin=None, nout=None):
if not nin:
nin = bar
if not nout:
nout = bar
return foo * nin / nout
它接受两个可选参数,如果它们没有传入,我需要将它们映射到另一个强制参数。但这是 pythonic 的方式吗?是否有其他方式获取检查并设置 nin 和 nout?
请您参考如下方法:
如果你真的想缩短它,你可以这样做:
nin = bar if nin is None else nin
请注意,我在这里通过identity 测试None,使用is,而不是truthiness;否则,如果例如nin = 0?这不是 None,但仍然评估 false-y(参见 truth value testing ),因此 style guide的建议:
Comparisons to singletons like
Noneshould always be done withisoris not... beware of writingif xwhen you really meanif x is not None-- e.g. when testing whether a variable or argument that defaults toNonewas set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
