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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With