Byoungchan Lee
Byoungchan Lee

Reputation: 1502

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?

Upvotes: 8

Views: 9828

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83716

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)

Upvotes: 4

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

The warning is from value1, value2 = result which would error if your function returned None. You can just 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 None is if b is None so the else seems redundant. I also presume the return get_something(a) logic is in a function.

Upvotes: 0

Related Questions