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

发布于 2025-01-12 02:16:04 字数 842 浏览 0 评论 0原文

我正在尝试做代码分析器应用程序,我有一个包含 python 代码的 txt 文件,我现在的目标是将这个 txt 文件中的所有函数保存在类的字典中,但我不知道如何才能首先

,我创建名为 class CodeAnalyzer: 的类

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

,并且我想将函数保存在 self.file_func= {}

,这是流程步骤,每个方法都应该返回键以及属性的增值

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)

这是我试图做的但 ie 失败了:

def store_function(self,i,line):
            if(line.startswith('def')):
                self.file_func.setdefault(i,[]).append((self.file_string[file_string.index(':') ,:]))

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

I'm trying to do code analyzer app and i have a txt file that contains a python code and my goal now is to save all functions in this txt file in dictionary in the class, but i don't have any idea how can i do it

at first i create class that name is class CodeAnalyzer:

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

and i want to save function in self.file_func= {}

this is process step, every method should return key and value added to attributes

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)

This what i tried to do but ie's failed :

def store_function(self,i,line):
            if(line.startswith('def')):
                self.file_func.setdefault(i,[]).append((self.file_string[file_string.index(':') ,:]))

Any one have an Idea or help on it ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨后彩虹 2025-01-19 02:16:04

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

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

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

You can just use exec() with it's globals() dict set to your class instance's namespace.

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

Feel free to comment on this answer if you have further questions.

黯淡〆 2025-01-19 02:16:04

我认为 isinstance 检查应该是

self.functions={i:self.namespace[i] for i in self.namespace if isinstance(self.namespace[i],type(lambda:0))}

我们想要测试 self.namespace 的第 i 个元素,而不是 i 的值。

I think the isinstance check should be

self.functions={i:self.namespace[i] for i in self.namespace if isinstance(self.namespace[i],type(lambda:0))}

we want to test the i-th element of the self.namespace, not the value of i.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文