I created a tool to examine Python 3 source code. It measures the density of program. More info in docstring (to not reinvent the wheel).
What could be done to increase its usability? Any edge cases that I didn't think of?
#!/usr/bin/env python3
'''
Module counts how dense is Python source code in
terms of lexical entities per LoC.
'''
import ast
def traverse(node, line_nos):
'''
go through the AST and count lines
'''
children = list(ast.iter_child_nodes(node))
try:
current_line = node.lineno
except AttributeError:
current_line = 0
count = 1
line_nos.update([current_line])
if len(children) == 0:
return 1
for child in ast.iter_child_nodes(node):
count += traverse(child, line_nos)
return count
def count_code_entities(source):
'''
parse the source&count
'''
line_nos = set()
tree = ast.parse(source)
# len - 1 to compensate for default value 0
# which cannot hold any code
return traverse(tree, line_nos), len(line_nos) - 1
def main():
'''
parsin&stuff
'''
from argparse import ArgumentParser, FileType
parser = ArgumentParser()
parser.add_argument('infile',
help='source file to analyze',
type=FileType(),
default='-',
nargs='?',)
args = parser.parse_args()
with args.infile as file:
source = file.read()
name = file.name
count, number = count_code_entities(source)
print(name, ': ', round(count/number, 4), 'entities/line of code')
if __name__ == '__main__':
main()
getattr
rather than atry except
. So I look forward to the answers to this question! :) \$\endgroup\$