Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to count number of functions of a python file, given path

Tags:

python

parsing

I do not want to import my module. I have to count the number of functions given the .py file path. What is the best way to do so?

One thing I thought about was to count the number of "def" in my code, but it does not seem like the best way to go about this. Is there any better way to count the number of functions?

like image 703
Lana Avatar asked Jan 07 '23 00:01

Lana


2 Answers

To count the top level definition, use ast module like this:

import ast

with open(filename) as f:
    tree = ast.parse(f.read())
    sum(isinstance(exp, ast.FunctionDef) for exp in tree.body)
like image 132
malbarbo Avatar answered Jan 11 '23 22:01

malbarbo


You can use ast.NodeVisitor:

import inspect
import importlib
import ast

class CountFunc(ast.NodeVisitor):
    func_count = 0
    def visit_FunctionDef(self, node):
        self.func_count += 1


mod = "/path/to/some.py"

p = ast.parse(open(mod).read())

f = CountFunc()
f.visit(p)

print(f.func_count)

If you wanted to include lambdas you would need to add a visit_Lambda:

 def visit_Lambda(self, node):
    self.func_count += 1

That will find all defs including methods of any classes, we could add more restrictions to disallow that:

class CountFunc(ast.NodeVisitor):
    func_count = 0

    def visit_ClassDef(self, node):
        return 

    def visit_FunctionDef(self, node):
        self.func_count += 1


    def visit_Lambda(self, node):
        self.func_count += 1

You can tailor the code however you like, all the nodes and their attributes are described in the greentreesnakes docs

like image 44
Padraic Cunningham Avatar answered Jan 12 '23 00:01

Padraic Cunningham