Couting the number of lines of code of a python program

chaouche yacine yacinechaouche at yahoo.com
Sat Jan 5 10:17:47 EST 2013


The idea started off as a volumetric information of my projects, but evolved to a sort of code browser that would display classes, methods and functions in a tree-like structure, and now I mostly want to use it with other people's code as a way to have the big picture. So I would say that it is used both for my programs (to get a feeling of their size) as much as it is used for others' code.

> But counting lines of code is a hairy thing to do. Do blank lines,
> comments, and multi-line strings count?

The way I implmented it, they do not, particulary docstrings (even though it seems that many people think docstrings are actual code). My opinion on docstrings is that they're not instructions. I want to know how many lines of instructions a program has. Comments, blank lines and docstrings are not intructions.

Here is my implementation :

defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line =line.strip()ifline ==""\ orline.startswith("#")\ ordocstring andnot(line.startswith('"""')orline.startswith("'''"))\ or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# this is either a starting or ending docstringelifline.startswith('"""')orline.startswith("'''"):docstring =notdocstring continueelse:nb_lines +=1returnnb_lines



----- Original Message -----
From: Chris Angelico <rosuav at gmail.com>
To: python-list at python.org
Cc: 
Sent: Saturday, January 5, 2013 3:09 PM
Subject: Re: Couting the number of lines of code of a python program

On Sun, Jan 6, 2013 at 12:55 AM, chaouche yacine
<yacinechaouche at yahoo.com> wrote:
> The
>  problem is that I'm using the inspect module, because it provides a
> nice function inspect.getsourcelines that takes a python object and
> return its number of lines of code. BUT, it works on live objects, that
> means one has to first import the module he wants to process, and this
> can have side effects (example : GUI programs).

If you're using this entirely on your own code, one good way to solve
the problem is to make your code always importable. Protect your
top-level code with "if __name__=='__main__':" (and possibly put it
into a function main() if that simplifies your code counting), and you
should then be able to import it as-is, and all you'll do is define ams and 
bunch of functions/classes.

But counting lines of code is a hairy thing to do. Do blank lines,
comments, and multi-line strings count?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list