A simply utility script which allows you to analyze your Python file
Tired of manually searching through your Python code? Wish you could quickly get insights into your file’s structure and contents? Look no further! This article presents a straightforward utility script that will analyze your Python files and provide you with valuable information.
Understanding the Need
As your Python projects grow, keeping track of function definitions, import statements, and class structures can become a daunting task. Manually searching through large files for specific elements is inefficient and time-consuming. A well-crafted analysis script can streamline this process, offering a clear overview of your code’s key components.
The Script
“`python
import ast
def analyze_python_file(file_path):
“””Analyzes a Python file and prints insights about its contents.
Args:
file_path (str): The path to the Python file.
“””
with open(file_path, ‘r’) as file:
source_code = file.read()
Parse the source code using the ast module
tree = ast.parse(source_code)
Function definitions
functions = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
print(“Function definitions:”)
for function in functions:
print(f” – {function}”)
Class definitions
classes = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]
print(“\nClass definitions:”)
for cls in classes:
print(f” – {cls}”)
Import statements
imports = [node.names[0].id for node in ast.walk(tree) if isinstance(node, ast.Import)]
print(“\nImport statements:”)
for imp in imports:
print(f” – {imp}”)
Other insights (optional):
– Count lines of code
– Identify variable usage
– Analyze code complexity
if __name__ == “__main__”:
file_path = input(“Enter the path to the Python file: “)
analyze_python_file(file_path)
“`
Breakdown
1.Import `ast`: The `ast` (Abstract Syntax Tree) module allows us to parse Python code and access its structural elements.
2.`analyze_python_file` function:
– Takes the file path as input.
– Opens the file and reads its contents.
– Parses the code using `ast.parse`.
– Iterates through the AST using `ast.walk` to identify:
– Function definitions: Using `ast.FunctionDef`.
– Class definitions: Using `ast.ClassDef`.
– Import statements: Using `ast.Import`.
– Prints the discovered elements in an organized manner.
3.Main block:
– Prompts the user to enter the file path.
– Calls the `analyze_python_file` function with the provided path.
Extending the Functionality
This script provides a basic framework for analyzing Python files. You can customize it further by:
– Counting lines of code: Use `source_code.splitlines()` to get the number of lines.
– Analyzing code complexity: Utilize the `complexity` module to calculate metrics like cyclomatic complexity.
– Identifying variable usage: Traverse the AST and track variable assignments and references.
– Adding more features: Perhaps you want to extract docstrings, identify potential issues, or generate code visualizations.
Conclusion
This simple utility script empowers you to quickly analyze your Python files, gaining insights into their structure and contents. With its straightforward approach and potential for expansion, it becomes a valuable tool for understanding and managing your Python projects more effectively. Go ahead, customize this script to suit your specific needs and enjoy the power of automated code analysis!