PyLint:尝试解包非序列
PyLint: Attempting to unpack a non-sequence
我是 PyLint 的新手,很高兴在我的源代码上看到很多警告。尽管大多数警告都很明显,但有些警告对我来说没有意义。例如,
def foo(a, b):
if b is not None:
return a, b
else:
return None
result = foo(a, b)
if result is None:
return get_something(a)
value1, value2 = result
foo(a, b)
的 return 值可以是元组或 None。从 foo
得到 return 值后,我检查它是否是有效结果。 (在 C/C++ 中检查 NULL
指针有点类似)但是,PyLint 抱怨这样的代码; Attempting to unpack a non-sequence [W:unpacking-non-sequence]
是否可以避免此类警告,除了抑制此警告?
这有点没有答案,但这就是我编写这段代码的方式。最重要的是,代码必须是可预测的,我发现总是 returning 相同数量的 return 值是可预测的。这也使文档更容易,以下代码也更短。
def foo(a, b):
if b is not None:
return a, b
return None, None
value1, value2 = foo(a, b)
if value1 is None: # Alt: value1 is None or value2 is None
return get_something(a)
警告来自 value1, value2 = result
如果您的函数 returned None 将会出错。您可以 return a,b 并检查 b 是否为 None:
def foo(a, b):
return a, b
value1, value2 = foo(a, b)
if value2 is None:
return get_something(a)
# else use value1 and value2
你的函数 returns None 的唯一方法是如果 b 是 None 所以 else 似乎是多余的。我还假设 return get_something(a)
逻辑在函数中。
我是 PyLint 的新手,很高兴在我的源代码上看到很多警告。尽管大多数警告都很明显,但有些警告对我来说没有意义。例如,
def foo(a, b):
if b is not None:
return a, b
else:
return None
result = foo(a, b)
if result is None:
return get_something(a)
value1, value2 = result
foo(a, b)
的 return 值可以是元组或 None。从 foo
得到 return 值后,我检查它是否是有效结果。 (在 C/C++ 中检查 NULL
指针有点类似)但是,PyLint 抱怨这样的代码; Attempting to unpack a non-sequence [W:unpacking-non-sequence]
是否可以避免此类警告,除了抑制此警告?
这有点没有答案,但这就是我编写这段代码的方式。最重要的是,代码必须是可预测的,我发现总是 returning 相同数量的 return 值是可预测的。这也使文档更容易,以下代码也更短。
def foo(a, b):
if b is not None:
return a, b
return None, None
value1, value2 = foo(a, b)
if value1 is None: # Alt: value1 is None or value2 is None
return get_something(a)
警告来自 value1, value2 = result
如果您的函数 returned None 将会出错。您可以 return a,b 并检查 b 是否为 None:
def foo(a, b):
return a, b
value1, value2 = foo(a, b)
if value2 is None:
return get_something(a)
# else use value1 and value2
你的函数 returns None 的唯一方法是如果 b 是 None 所以 else 似乎是多余的。我还假设 return get_something(a)
逻辑在函数中。