count lines of code for each class in a python file?

1.3k Views Asked by At

I'm trying to find the count of lines of codes within a class in a python file .. I used the len(inspect.getsourcelines(b)[0]) to return the number of lines of code for each class in the file but the problem it counts comments and doc string in addition to the code lines .. is there any way to discard the comments and doc string??

import inspect
import foo

for a,b in inspect.getmembers(foo): 
    if inspect.isclass(b):
        print(a)
        print(len(inspect.getsourcelines(b)[0]))
1

There are 1 best solutions below

3
On

You may just have to parse out the comments yourself from the result of getsourcelines. If you ignore multiline comments, this just means checking if the first non-whitespace character is #. For multiline comments using triple quotes, you can do something similar while keeping track of whether or not you're in a comment block.