【发布时间】:2022-11-17 05:11:04
【问题描述】:
考虑以下用例(最小示例):
def get_func(param):
if param is None:
def func():
return None
else:
def func():
return param
return func
def process_val(param):
func = get_func(param)
val = func()
# Do stuff with 'val'; *None* is an useful case.
return val
这里,功能()可以退货没有任何或不,取决于价值参数,但是 Pylint 为此触发了 E1128,解释如下:
当在函数调用上完成赋值但推断的函数只返回 None 时使用。
我很想禁用此代码的警告,但它实际上被归类为错误,这让我觉得这实际上在过去产生了错误,所以我想了解:这是一个 Pylint 错误吗?看不到有时创建的函数会返回其他东西没有任何?或者它被认为是太糟糕的做法,可能有一个总是返回的函数没有任何?也许我看不到其他一些解释?
如果这看起来太复杂了,实际用例更像这样:
def get_func(source): if source is None: def func(): return None elif source is "webcam": # Open webcam... def func(): # Capture frame from webcam return frame elif source is "server": # Open connection to server... def func(): # Read data from server. return data # Other cases... return func def process_val(source): data_func = get_func(source) # Here, do stuff in a loop, or pass *data_func* to other functions... # The code that uses the *data_func* knows that *None* means that # data could not be read and that's OK.对于使用的代码数据函数,这样比必须考虑的值更简单资源决定数据是否永远没有任何.对我来说这似乎是有效的功能风格方法(也许我错了,这不是 Pythonic 方式)。
(我正在使用 Pylint 2.12.2)
【问题讨论】: