Reputation: 498
When you run pylint on code like this
#!/usr/bin/env python3
def func1(string):
split = []
for sub in string.split(" "):
split.append(sub)
return split
def main(string):
a, b, c, d = func1(string)
print(a, b, c, d)
if __name__ == '__main__':
input1 = "some random words !"
# note that the string will always contain exactly three spaces
assert input1.count(" ") == 3
main(input1)
you receive the message:
Possible unbalanced tuple unpacking with sequence defined at line 4: left side has 4 label(s), right side has 0 value(s)
(unbalanced-tuple-unpacking)
As the warning states, a unbalanced tuple unpacking is possible here. In this case, it won't happen in reality due to the assertion. Different other solutions state that one could disable this exact warning via the configuration (s. Pylint warning: Possible unbalanced tuple unpacking with sequence) to solve this. However, I would rather avoid disabling it since the warning might be useful at another point in the code. Hence, I tried a few things and one solution that avoids this message is:
#!/usr/bin/env python3
def func1(string):
split = []
for sub in string.split(" "):
split.append(sub)
return split
def main(string):
# note the * operator
a, b, c, d, *_ = func1(string)
print(a, b, c, d)
if __name__ == '__main__':
input1 = "some random words !"
# note that the string will always contain exactly three spaces
assert input1.count(" ") == 3
main(input1)
However, this appears like a rather ugly workaround to me. Do you agree? If so do you have other solutions to avoid the warning?
Upvotes: 0
Views: 816
Reputation: 563
PyLint is unhappy because you are dynamically appending to a list, as opposed to creating a one-off list. To fix this, you can create a one-off list by using either a comprehension or the list type.
To fix your example:
def func1(string):
split = list(string.split(" "))
return split
def main(string):
a, b, c, d = func1(string)
print(a, b, c, d)
if __name__ == '__main__':
input1 = "some random words !"
# note that the string will always contain exactly three spaces
assert input1.count(" ") == 3
main(input1)
Upvotes: 1