一个函数正在接收许多都是字符串但需要以各种方式解析的值,例如
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 函数?即使没有,像这样的函数是否有一个常用的名称?