Lines of code are a bad measurement for anything, for reasons not discussed here. But is there a neat way to count statements in a Python source code file?
Asked
Active
Viewed 1,174 times
0
-
So what do you want to exclude? Blank lines and comments? All comments (including docstrings)? – Gareth Latty May 04 '12 at 18:38
-
Everything which is not meaningful for the application control flow (blank lines, comments, etc.) Also counting ; separated statements. – Mikko Ohtamaa May 04 '12 at 18:39
-
1Possible repeat: http://stackoverflow.com/questions/5764437/python-code-statistics – May 04 '12 at 18:42
-
1the number of statements/expressions is equally misleading as the lines of code I think... – moooeeeep May 04 '12 at 19:57
4 Answers
3
pylint gives in its output report directly:
pylint main.py
...
Report
======
145 statements analysed.

Mikko Ohtamaa
- 82,057
- 50
- 264
- 435
-
1Is there any way to obtain only statement count from Pylint ? `Pylint --reports=y main.py` results all messages along with statement count. – YatShan Jan 01 '20 at 02:42
1
Use the ast
module that parses and constructs the syntax tree from Python code. You will be able to apply the customized counting algorithm you would like based on that tree and the nodes.

Zeugma
- 31,231
- 9
- 69
- 81
0
To count physical lines of code (as opposed to locical lines of code) I have found SLOCCount to give reasonable numbers.

Ulf Rompe
- 919
- 6
- 8
-
Yes, but this number is useless and SO it not right place to have conversation why it is useless – Mikko Ohtamaa May 04 '12 at 20:12
-
@MikkoOhtamaa On the contrary, if you're going to complain about solutions, you had better give some reasons. – Marcin May 04 '12 at 22:18
0
Although this is an old post. Here is a snippet of code that counts the statements in a python source file in the same way as PyLint does.
from astroid import MANAGER
# Tested with astroid 2.3.0.dev0
class ASTWalker:
"""
Class to walk over the Astroid nodes
"""
def __init__(self):
self.nbstatements = 0
def walk(self, astroid_node):
"""
Recurse in the astroid node children and count the statements.
"""
if astroid_node.is_statement:
self.nbstatements += 1
# recurse on children
for child in astroid_node.get_children():
self.walk(child)
walker = ASTWalker()
ast_node = MANAGER.ast_from_file("/my/file/name", source=True)
walker.walk(ast_node)
print(walker.nbstatements)

andresperezcba
- 1
- 2