在 python 中以最简单的方式检查无法访问的代码

check unreachable code in most simple way in python

我有一个 python 代码,用于检测保存在 txt 文件中的另一个 python 代码中的任何错误,我做到了,我可以检测函数中的幻数和超过 3 个参数,并且现在我必须检查无法访问的代码,但我不知道该怎么做,我想检测函数中 return 之后是否有代码,我尝试了几次,但都失败了

这条主要 class :

class CodeAnalyzer:
    def __init__(self, file):
        self.file = file
        self.file_string = ""
        self.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) 

例如这是检查参数函数,我需要写一个类似的但要检测无法访问的代码:

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

任何人都可以提供帮助并有想法吗?

可能您必须使用 ast 模块来查看解析树。

寻找:

  • ifwhile 语句的条件总是 False。 (或者在 else 的情况下总是 true)这将涉及“常量传播”,即实现仅依赖于常量的表达式本身是常量。
  • return 之后的代码,return 不属于 if
  • 函数末尾的代码在模块上下文中缩进不正确。

或者你可以看看 mypy 是怎么做的。