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

Jon*_*sen 3 python nonetype

一个函数正在接收许多都是字符串但需要以各种方式解析的值,例如

vote_count = int(input_1)
score = float(input_2)
person = Person(input_3)
Run Code Online (Sandbox Code Playgroud)

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

vote_count = int(input_1) if input_1 is not None else None
...
Run Code Online (Sandbox Code Playgroud)

但这似乎不太可读,尤其是像这样的许多重复行。我正在考虑定义一个简化这个的函数,比如

def whendefined(func, value):
    return func(value) if value is not None else None
Run Code Online (Sandbox Code Playgroud)

可以像这样使用

vote_count = whendefined(int, input_1)
...
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*Joe 5

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

在 Python 中,更多地关注此类事情的运行时检测,因此您可以使用无检测保护(而不是 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
Run Code Online (Sandbox Code Playgroud)

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

正在使用:

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

>>> optionprint(None)
# Nothing

>>> optionprint("hello")
'hello!!'
Run Code Online (Sandbox Code Playgroud)

并带有返回值

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

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

>>> optioninc(100)
101
Run Code Online (Sandbox Code Playgroud)

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

>>> int_or_none = option(int)
>>> int_or_none(None)
# Nothing
>>> int_or_none(12)
12
Run Code Online (Sandbox Code Playgroud)