Search code examples
pythonpython-3.xpython-2.7dictionarydead-code

check unreachable code in most simple way in python


I have a python code with is detect any errors in another python code saved in txt file, i did that i can detect magic numbers and more than 3 parameters in the function, and now i have to check un reachable code, but i don't have an idea how can i do it, i want to detect if there's a code after return in the function, i did several attempts and all of them failed

This main class :

class CodeAnalyzer:
    def __init__(self, file):
        self.file = file
        self.file_string = ""
        self.errors = {}

this is a method where it's pass detects function so i can print errors :

 def process_file(self):
        for i, line in enumerate(self.file):
            self.file_string += line
            self.check_divide_by_zero(i, line)
            self.check_parameters_num(i, line) 

and for example this is check parameter function, i need to write similar one but to detect unreachable code :

  def check_parameters_num(self, i, line):
            count = line.count(",")
            if(line.startswith('def') and count+1 >= 3):
                self.errors.setdefault(i, []).append(('S007', '')) 

Any one can help and have an idea ?


Solution

  • Probably you would have to use the ast module to look at the parse tree.

    Look for:

    • Conditions for if and while statements that are always False. (or always true in case of an else) This would involve "constant propagation", that is realizing that an expression that only depends on constants is itself constant.
    • Code after a return, without that return being part of an if.
    • Code at the end of a function that is indented incorrectly an thus in the module context.

    Or you could look at how mypy is doing it.