A good way to count the number of functions of a python file given a path

I do not want to import my module. I need to count the number of functions given in the .py path. What is the best way to do this?

One thing I was thinking about is counting the amount of "def" in my code, but that doesn't seem like the best way to do this. Is there a better way to count the number of functions?

+4
source share
4 answers

To calculate the top-level definition, use the module astas follows:

import ast

with open(filename) as f:
    tree = ast.parse(f.read())
    sum(isinstance(exp, ast.FunctionDef) for exp in tree.body)
+3
source

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 want to enable lambdas, you need to add visit_Lambda:

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

defs, , , :

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

, , greentreesnakes docs

+3

Padraic , , Python 2 Python 3.

from __future__ import print_function
import ast

class FunctionCounter(ast.NodeVisitor):
    def __init__(self, filename):
        self.function_count = 0
        with open(filename) as f:
            module = ast.parse(f.read())
            self.visit(module)

    def visit_FunctionDef(self, node):
        print('function: {}'.format(node.name))
        self.function_count += 1

    # Uncomment this to disable counting methods, properties within a
    # class
    # def visit_ClassDef(self, node):
    #     pass

if __name__ == '__main__':
    counter = FunctionCounter('simple.py')
    print('Number of functions: {}'.format(counter.function_count))

  • , ( ), .
  • , 2 visit_ClassDef
+1

pyclbr , , , , from X import Y python ( , math)

from pyclbr import readmodule_ex, Function
#readmodule_ex is function 1

def test(): #2
    pass
def other_func(): #3
    pass

class Thing:
    def method(self):
        pass


result = readmodule_ex("test") #this would be it own file if it is test.py

funcs = sum(isinstance(v,Function) for v in result.values())

print(funcs)
0
source