Python: code statistics

前端 未结 3 1936
花落未央
花落未央 2021-02-07 22:27

Do you know if there\'s a Python library that generates statistics about code? I\'m thinking about pointing to a package and getting number of classes, functions, methods, docbl

3条回答
  •  被撕碎了的回忆
    2021-02-07 23:26

    People don't generally make packages out of things that can be done in a dozen or two lines of code. The following analyzes usage of all python syntax and returns a dictionary mapping ast nodes to how many times that node came up in the source. Examples showing the number of def and class statements are below it as well.

    import collections
    import os
    import ast
    
    def analyze(packagedir):
        stats = collections.defaultdict(int)
        for (dirpath, dirnames, filenames) in os.walk(packagedir):
            for filename in filenames:
                if not filename.endswith('.py'):
                    continue
    
                filename = os.path.join(dirpath, filename)
    
                syntax_tree = ast.parse(open(filename).read(), filename)
                for node in ast.walk(syntax_tree):
                    stats[type(node)] += 1   
    
        return stats
    
    print("Number of def statements:", analyze('.')[ast.FunctionDef])
    print("Number of class statements:", analyze('.')[ast.ClassDef])
    

提交回复
热议问题