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
ifandwhilestatements that are alwaysFalse. (or alwaystruein case of anelse) 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 anif. - 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.