Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve pylint (too-many-return-statements) elegantly?

Tags:

python

pylint

enter image description here The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful?

def func():
    # do something1
    ret1 = do_something1()
    if ret1 != 0:
        return ret1

    # do something2
    ret2 = do_something2()
    if ret2 != 0:
        return ret2
    # ......
    return 0
like image 498
zcfh Avatar asked Nov 02 '25 06:11

zcfh


2 Answers

You could try something like this:

def foo(x):
    nums = ['one','two','three','four','five','six','seven']
    return 'This is ' + nums[x-1]

to solve your example. And you could solve your scenario like this:

def func():
    functions = [do_something1,do_something2,...]
    for function in functions:
        ret = function()
        if ret != 0:
            return ret
    return 0
like image 67
Jhanzaib Humayun Avatar answered Nov 03 '25 22:11

Jhanzaib Humayun


Check out this example.

It converted:

def func(x):
    if x == 1:
        return "hi1"
    if x == 2:
        return "hi2"
    if x == 3:
        return "hi3"
    if x == 4:
        return "hi4"
    if x == 5:
        return "hi5"
    if x == 6:
        return "hi6"
    if x == 7:
        return "hi7"

to:

d = {1: "hi1", 2: "hi2", 3: "hi3", 4: "hi4", 5: "hi5", 6: "hi6", 7: "hi7"}
def func(x):
    return d[x]

Just to silence it another option is:

def func(x):
    if x == something1:
        res = "something1"
    elif x == something2:
        res = "something2"
    elif x == something3:
        res = "something3"
    elif x == something4:
        res = "something4"
    elif x == something5:
        res = "something5"
    elif x == something6:
        res = "something6"
    elif x == something7:
        res = "something7"
    else:
        res = "default"
    return res

You can also silence it in settings.json file if you think it's too strict rule which I think it is:

    "python.linting.pylintArgs": [
        "--disable=R0911"
    ],
like image 26
SorousH Bakhtiary Avatar answered Nov 03 '25 22:11

SorousH Bakhtiary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!