project_ananthu project_ananthu - 1 month ago 4
Python Question

How to find exceptions in code that is not executed?

In this simple Python code if the value of

a
is changed from
0
then there will be a
NameError
showing that
b
is undefined. However, if the
else
clause is never executed, the error remains hidden. How can I detect these kind of errors?

a=0
if a==0 :
print "hello"
else :
print b

Answer

pylint is able to find a lot of common (and not so common) errors in python code without executing it, example output from your example:

C:  1, 0: Exactly one space required around assignment
a=0
 ^ (bad-whitespace)
C:  2, 0: Exactly one space required around comparison
if a==0 :
    ^^ (bad-whitespace)
C:  2, 0: No space allowed before :
if a==0 :
        ^ (bad-whitespace)
C:  4, 0: No space allowed before :
else :
     ^ (bad-whitespace)
C:  1, 0: Missing module docstring (missing-docstring)
C:  1, 0: Invalid constant name "a" (invalid-name)
E:  5,10: Undefined variable 'b' (undefined-variable)

The line you're interested in here is: E: 5,10: Undefined variable 'b' (undefined-variable)

Comments