如果 None,则将可选参数映射到强制参数的 Pythonic 方法

Pythonic way to map optional parameters to a compulsory one if None

我有这样的功能:

def func(foo, bar, nin=None, nout=None):
    if not nin:
        nin = bar
    if not nout:
        nout = bar
    return foo * nin / nout

它有两个可选参数,如果没有传入,我需要将它们映射到另一个强制参数。但这是pythonic的方式吗?是否有其他方法来获取检查并设置 ninnout

我会做以下事情:

def func(foo, bar, nin=None, nout=None):
    nin = bar if nin is None else nin
    nout = bar if nout is None else nout
    return foo * nin / nout

None 是您也接受零等的输入方式。

我认为你应该使用 nin is None 而不是 nin == None,许多人会争辩说 nin = bar if nin is None else nin 更像 pythonic,但我个人认为两者都可以。

如果你真的想缩短它,你可以这样做:

nin = bar if nin is None else nin

请注意,我在这里通过 identity 测试 None,使用 is,而不是 truthiness ;否则,如果例如nin = 0?这不是 None,但仍然评估 false-y(参见 truth value testing), hence the style guide 的建议:

Comparisons to singletons like None should always be done with is or is not ... beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!