Created
March 3, 2024 16:55
-
-
Save oduvan/ba7f3bf5e5351648e7b6d3bbe8ab771d to your computer and use it in GitHub Desktop.
Find Top 10 longest functions in your source folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
def find_functions(file_path): | |
""" | |
Extracts functions and their line counts from a given Python file. | |
""" | |
with open(file_path, 'r') as file: | |
lines = file.readlines() | |
current_func = None | |
indent_level = None | |
total_lines = 0 | |
for line in lines: | |
stripped_line = line.lstrip() | |
indent = len(line) - len(stripped_line) | |
if current_func and stripped_line and indent <= indent_level: | |
yield (file_path, current_func, total_lines) | |
current_func = None | |
if not current_func and stripped_line.startswith("def "): | |
current_func = stripped_line.split("(")[0][4:] | |
indent_level = indent | |
total_lines = 1 | |
elif current_func: | |
if not stripped_line: | |
pass | |
total_lines += 1 | |
if current_func: | |
yield (file_path, current_func, total_lines) | |
def find_largest_function_in_directory(directory): | |
largest_function = None | |
largest_line_count = 0 | |
largest_function_file = "" | |
all_functions = [] | |
for root, _, files in os.walk(directory): | |
for file in files: | |
if file.endswith(".py"): | |
file_path = os.path.join(root, file) | |
functions = find_functions(file_path) | |
all_functions += list(find_functions(file_path)) | |
return sorted(all_functions, key=lambda a: a[-1], reverse=True)[:10] | |
from pprint import pprint | |
pprint(find_largest_function_in_directory('django/django')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment