Weholt
Weholt

Reputation: 1989

Getting start/end of a python class from source

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.

Upvotes: 2

Views: 642

Answers (2)

ncoghlan
ncoghlan

Reputation: 41586

I suggest using the standard library Python class browser (pyclbr) as a starting point.

Upvotes: 2

Joshua Fox
Joshua Fox

Reputation: 19705

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

Upvotes: 0

Related Questions