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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With