从源代码获取 python 类的开始/结束
假设我有一个文件,其中定义了几个类,如下所示:
class A:
def somemethod(self): pass
...more methods...
class B:
def othermethod(self): pass
....even more methods...
如何找出源代码 A 类中的哪一行开始和结束,B 类代码的哪一行开始和结束?如果将文件加载到编辑器中,标记文本“Class A”,并希望在 A 类定义末尾的源代码中插入一个方法,我该怎么做?我认为以纯文本文件形式阅读源代码效果不太好。
有没有办法在不导入和检查的情况下找出定义了哪些类、它们实现的方法、它们的子类等?
底线:我需要找出事物的开始和结束位置,以便能够操作源代码,例如向类添加方法,向现有方法添加装饰器,从现有类中提取所有方法并使用相同的方法创建新的方法 。
目标是在 python IDE/编辑器中创建智能感知
Say I got a file with a few classes defined in it, like so:
class A:
def somemethod(self): pass
...more methods...
class B:
def othermethod(self): pass
....even more methods...
How can I find out which line in the source Class A starts and ends, which line of code Class B start and ends? If load the file into an editor, marks the text "Class A" and want to insert a method into the source at the end of the definition of Class A, how do I do that? I do not think reading the source as a plain text-file will work very well.
Are there ways to find out what classes are defined, methods they implement, what classes they subclass etc without importing and inspecting?
The bottom line: I need to find out where things start and end to be able to manipulate the source, for instance add methods to classes, add decorators to existing methods, extract all methods from an existing class and creating a new with the same methods etc.
Goal is to create intellisense in a python IDE/Editor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用标准库Python类浏览器(
pyclbr
)作为起点。I suggest using the standard library Python class browser (
pyclbr
) as a starting point.从解析抽象语法树的角度思考,而不是从原始行的角度思考。即使Python,其基于行而不是基于括号的语法,也可以用分号将多个语句排列在一行上,或者用反斜杠将一条语句跨两行排列。
有很多方法可以做到这一点,但请参阅内置包 ast
Think in terms of parsing the Abstract Syntax Tree, not in terms of raw lines. Even Python, with its line- rather than brackets-based syntax, can arrange multiple statements on a line with semicolon, or spread a statement across two lines with backslash.
There are many ways to do this, but see built-in package ast