Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading