Search code examples
pythonif-statementtestingpylintraise

Multiple if-raise statement


I wrote a python code with the following format:

if a1 in list1:
    if b1 == 1 and c1>1:
        raise Exception ('invalid c1 for b1')
    elif b1 == 2 and c1>2:
        raise Exception ('invalid c1 for b1')
    elif b1 == 3 and c1>3:
        raise Exception ('invalid c1 for b1')
    else
        z = c1 * d * f
else:
    raise Exception ('invalid a1')

I performed a pylint test on my code and it shows an error that "Unnecessary "elif" after "raise". change "elif" to "if"". I did it like the following code:

if a1 in list1:
    if b1 == 1 and c1>1:
        raise Exception ('invalid c1 for b1')
    if b1 == 2 and c1>2:
        raise Exception ('invalid c1 for b1')
    if b1 == 3 and c1>3:
        raise Exception ('invalid c1 for b1')
    else
        z = c1 * d * f
else:
    raise Exception ('invalid a1')

now, pylint says "Unnecessary "else" after "raise", remove the "else" and de-indent the code inside it". I am not keen to do that because two "else" statements dealing for two different situations. I am wondering if there is any better method to implement this code that pylint won't raise any issues. (I am aware I can disable pylint errors using "#pylint disable=..." but this is not my first option)


Solution

  • The pylint warning is about the first else, not the second. So it is suggesting to write your code like this:

    if a1 in list1:
        if b1 == 1 and c1>1:
            raise Exception ('invalid c1 for b1')
        if b1 == 2 and c1>2:
            raise Exception ('invalid c1 for b1')
        if b1 == 3 and c1>3:
            raise Exception ('invalid c1 for b1')
        z = c1 * d * f
    else:
        raise Exception ('invalid a1')
    

    ...which would be equivalent. The only way to get to the statement z = c1 * d * f is when the conditions in the three preceding if statements are all false.

    I am wondering if there is any better method to implement this code

    The above would do, but you could also save on one level of indentation by negating the first condition:

    if a1 not in list1:
        raise Exception ('invalid a1')
    if b1 == 1 and c1>1:
        raise Exception ('invalid c1 for b1')
    if b1 == 2 and c1>2:
        raise Exception ('invalid c1 for b1')
    if b1 == 3 and c1>3:
        raise Exception ('invalid c1 for b1')
    z = c1 * d * f
    

    And you can also combine conditions that lead to the same exception:

    if a1 not in list1:
        raise Exception ('invalid a1')
    if b1 in (1, 2, 3) and c1>b1:
        raise Exception ('invalid c1 for b1')
    z = c1 * d * f