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