PyLint: attempt to unpack a sequence

I'm new to PyLint, and I'm glad to see a lot of warnings on my source code. Although most warnings are obvious, some warnings do not for me. For instance,

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 value can be either a tuple or None. After getting the return value from foo , I check if it is a valid result or not. (This is similar to checking for a NULL pointer in C / C ++). However, PyLint complains about such code; Attempting to unpack a non-sequence [W:unpacking-non-sequence] Can such warnings be avoided besides warning this warning?

+5
source share
2 answers

This seems to be no answer, but I would write this piece of code. First of all, the code must be predictable, and I always return the same number of returned values ​​predictable. It also makes documentation easier, and the following code is a bit shorter.

 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) 
+4
source

Warning from value1, value2 = result , which will be erroneous if your function returns None. You can simply return a, b and check if b is 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 

The only way your function returns is No, if b is None, otherwise else seems redundant. I also assume that the logic return get_something(a) is in a function.

0
source

All Articles