lines of code within a class in python?
-
13-07-2021 - |
Question
I'm trying to find the number of lines of code within class or function that are stored in a python file my code is like this... what I want is to find number of lines of code in the a class not all the file ... is there any good way to do so??
import inspect
import foo
for a,b in inspect.getmembers(foo):
if inspect.isclass(b):
print a # find a class within the file
Solution
len(inspect.getsourcelines(a)[0])
From inspect.getsourcelines docs:
Return a list of source lines and starting line number for an object.
That's why you need the 0 index
OTHER TIPS
You can still use inspect
,
In [6]: from test import A
In [7]: import inspect
In [8]: inspect.getsourcelines(A)
Out[8]:
(['class A(object):\n',
' pass\n',
' pass\n',
' pass\n',
' pass\n',
' pass\n',
' pass\n',
' pass\n',
' pass\n'],
1)
len(inspect.getsourcelines(A)[0])
will return you want.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow