Search code examples
pythonpylint

PyLint: Attempting to unpack a non-sequence


I'm new to PyLint and I'm glad to see lots warnings on my sourcecode. Though most of warnings are obvious, some warnings are not making sence for me. For example,

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


Solution

  • This is kind of a no answer, but this is how I would write this piece of code. Foremost, the code must be predictable and I find always returning the same number of return values predictable. This also the documentation easier and the following code little 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)