Skip to main content
 首页 » 编程设计

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

2025年05月04日31傻小

我有这样一个函数:

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 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!