Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to programmatically get line number of class definition

Tags:

python

suppose I have a module named test.py. In this file, I know a class named dummy. How to get the line number of class dummy definition after I import it?

Is there an API can do such thing?

if dummy is a function, then dummy.__code__.co_firstlineno will return the line no. But if dummy is a class, it doesn't have__code__attribute

I wanna know is there a way which can return the line no without parsing the file.

like image 599
24April14 Avatar asked Feb 01 '17 04:02

24April14


1 Answers

inspect.findsource(test.dummy)[1] provides the line number via regex search in the source file (rather slow).

If you define the class, line numbers could be exposed like this:

class MyClass:
    def test_01(self):
        assert 1
    _classline_ = inspect.currentframe().f_code.co_firstlineno
    _thisline_ = inspect.currentframe().f_lineno

Update 2020 / Python 3.9+ : inspect.findsource now uses (slow) ast instead of regex. (bpo-35113 / commit 696136b9)

like image 158
kxr Avatar answered Oct 02 '22 21:10

kxr