0

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?

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435

4 Answers4

3

pylint gives in its output report directly:

  pylint main.py 

  ...

  Report
  ======
  145 statements analysed.
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • 1
    Is 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
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)