2

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]))
Udi
  • 29,222
  • 9
  • 96
  • 129
tkyass
  • 2,968
  • 8
  • 38
  • 57
  • You can access the docstring for each class and function via `__doc__` and count docstring lines yourself, but I don't know of a way to do that with comments. – Michael Foukarakis Oct 22 '12 at 00:02
  • 1
    it is better to include comments in the lines of code count. – wim Oct 22 '12 at 00:43

1 Answers1

2

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.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • I tried to do so but I couldn't find any way that can work ... do you have any idea of how to do so?? – tkyass Oct 22 '12 at 01:22
  • Ignoring multiline comments, `len([line for line in inspect.getsourcelines(foo)[0] if not line.strip().startswith('#')])` where foo is the object you're inspecting. – Michael Mior Oct 22 '12 at 02:26
  • If this is something you've tried, it would be good to post what you've tried that didn't work. – Michael Mior Oct 22 '12 at 02:26