Python 仅当值不是 None 时才应用函数的习语

Python idiom for applying a function only when value is not None

一个函数正在接收一些值,这些值都是字符串,但需要以各种方式进行解析,例如

vote_count = int(input_1)
score = float(input_2)
person = Person(input_3)

这一切都很好,除了输入也可以是 None,在这种情况下,我不想解析值,而是希望将 None 分配给左侧。这可以用

来完成
vote_count = int(input_1) if input_1 is not None else None
...

但这看起来可读性要差得多,尤其是像这样的重复行很多。我正在考虑定义一个函数来简化这个,比如

def whendefined(func, value):
    return func(value) if value is not None else None

可以像

一样使用
vote_count = whendefined(int, input_1)
...

我的问题是,这个有通用的成语吗?可能使用内置 Python 函数?即使没有,像这样的函数有常用的名称吗?

在其他语言中有 Option typing,它有点不同(解决类型系统的问题),但具有相同的动机(如何处理空值)。

在 Python 中,更多的重点是运行时检测这类事情,所以你可以用 None 检测守卫(而不是 Option 输入的数据)来包装函数确实)。

你可以编写一个装饰器,它只在参数不是 None:

时才执行一个函数
def option(function):
    def wrapper(*args, **kwargs):
        if len(args) > 0 and args[0] is not None:
          return function(*args, **kwargs)
    return wrapper

您可能应该调整第三行以更适合您正在处理的数据类型。

正在使用:

@option
def optionprint(inp):
    return inp + "!!"

>>> optionprint(None)
# Nothing

>>> optionprint("hello")
'hello!!'

并具有 return 值

@option
def optioninc(input):
    return input + 1

>>> optioninc(None)
>>> # Nothing

>>> optioninc(100)
101

或者包装一个类型构造函数

>>> int_or_none = option(int)
>>> int_or_none(None)
# Nothing
>>> int_or_none(12)
12

如果您可以安全地将虚假值(例如 0 和空字符串)视为 None,则可以使用布尔值和:

vote_count = input_1 and int(input_1)

因为看起来您正在接受字符串作为输入,所以这可能有效;无论如何,您不能将空字符串转换为 int 或 float(或 person)。对于某些人来说,它并不过分可读,尽管这个成语通常用于 Lua.