将 txt 文件中的所有函数体存储在 python 中的字典中

storing all function body from txt file in dictionary in python

我正在尝试开发代码分析器应用程序,我有一个包含 python 代码的 txt 文件,我现在的目标是将此 txt 文件中的所有函数保存在 [=31= 的字典中], 但我不知道该怎么做

起初我创建 class 名称是 class CodeAnalyzer:

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

我想在 self.file_func= {}

中保存函数

这是流程步骤,每个方法都应该return将键和值添加到属性

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 store_function(self,i,line):
            if(line.startswith('def')):
                self.file_func.setdefault(i,[]).append((self.file_string[file_string.index(':') ,:]))

有人对此有想法或帮助吗?

您可以只使用 exec() 并将其 globals() 字典设置为您的 class 实例的命名空间。

class CodeAnalyzer:
  def __init__(self,file):
    # Read a string from the file
    f=open(file)
    t=f.read()
    f.close()

    #Populate the namespace dictionary by executing the code in the file
    self.namespace={}#this includes all declarations of functions, variables and classes
    exec(t,self.namespace)#this means that when variables are declared, they use the class instance's attributes dictionary as their global namespace

    #Filter the namespace dict based on the contents
    self.functions={i:self.namespace[i] for i in self.namespace if isinstance(i,type(lambda:0))}#type(lambda:0) is just FunctionType
    self.classes={i:self.namespace[i] for i in self.namespace if isinstance(i,type)}#all classes are instances of type
    self.variables={i:self.namespace[i] for i in self.namespace if i not in self.functions|self.classes}#everything else, using dictionary merge

如果您还有其他问题,请随时对此答案发表评论。