简体   繁体   中英

Inconsistent return value Pylint

I have used pylint to check my code and I am receiving the following suggestion. 'Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)'. The code block is below. I am passing in a value and need to return which value range it belongs to. If I move the return value outside of the if it will return the incorrect count value. Any suggestions?

def findRangeValue(ranges, number):

    count = -1
    n = 2
    for x in range(len(ranges)-n+1):
        count += 1
        batch = range[x:x + n]
        if batch[0] < number <= batch[1]:
            return count
  • You need confirm the function always have a non-empty (not None ) return value in most common situation.
  • Your code will return None when all if statement in the loop failed, need add a final return value outside loop.

example code:

def findRangeValue(ranges, number):
    count = -1
    n = 2
    for x in range(len(ranges)-n+1):
        count += 1
        batch = ranges[x:x + n]
        if batch[0] < number <= batch[1]:
            return count
    return -1

print(findRangeValue([1,3,5,7,9], 4))
print(findRangeValue([1,3,5,7,9], 10))

result:

1
-1

Your function is written in a way, that it returns a value only if a condition is met ie .

if batch[0] < number <= batch[1]:

Assume a situation you are consuming the function something like

range_val = findRangeValue([1,2,3], 3)

If the condition was met the return value will be assigned to range_val . But if the condition was not met, then the function returns nothing and your range_val becomes None .

But your code expects it to be a number and not None . So, now you need to check the return value to avoid errors - an extra line of code.

Assume you are calling this function from various parts of your code, every where you need to bring in this check - more and more code.

To avoid this, a standard to follow is that, a function always returns what was promised. If it was not able to do so, raise an Exception so that, the caller is notified without an additional check.

In your particular scenario, you can use a break statement and always return a count outside (beware, if break was not met, the value could be not what you expect) Or use an additional flag variable with break, and raise an error if the flag variable was not set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM