0

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
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
tkyass
  • 2,968
  • 8
  • 38
  • 57

2 Answers2

3
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

  • thanks for the reply ... but I tried to run your code and it gave me error ... TypeError: 'Foo' is not a module, class, method, function, traceback, frame, or code object ... and 'Foo' is the name of the class in foo.py – tkyass Oct 21 '12 at 09:02
  • it's working now .. I had some syntax error .. thanks a lot for your help – tkyass Oct 21 '12 at 09:09
  • the problem with this approach is that it counts lines of codes and comments .. is there any way to count only lines of codes without comments and doc strings?? – tkyass Oct 21 '12 at 23:16
  • First thing that comes to my mind is to iterate over the lines and count only those that don't start with #. len([line for line in inspect.getsourcelines(a)[0] if not line.lstrip().startswith('#')]) – Alexander Stefanov Oct 22 '12 at 07:49
3

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.

iMom0
  • 12,493
  • 3
  • 49
  • 61
  • @user1762447 I recommend you read through the `inspect` docs first, then you will finish your code more efficiently. – iMom0 Oct 21 '12 at 09:14
  • believe me I tried to read the inspect docs several times but many things remain unclear to me.. I'm new to Python and this is why I think I'm still not familiar with Python docs . I have one more question I tried to modify the code you submited to make it count the lenghts of lones of codes only without the comments but it didnt work .. is there any way to do so?? may be by using inspect.getdocs and inspect.getcomment and subtract them? – tkyass Oct 21 '12 at 23:21
  • @user1762447 Comments and docs, or only comments? When you got list of code lines, remove both ends of the spaces, filter each line not starts with '#'. – iMom0 Oct 22 '12 at 00:49