206. AST (Abstract Syntax Trees) in Python
🔹 1. Parsing Python Code into an AST
Convert a Python expression into an AST tree.
import ast
code = "x = 5 + 3"
tree = ast.parse(code)
print(ast.dump(tree, indent=4))🔍 How it works:
ast.parse(code)generates an AST representation of the code.ast.dump(tree, indent=4)prints the AST structure in a readable format.
🔹 2. Extracting Function Names from Python Code
Traverse an AST to find all function definitions.
import ast
code = """
def greet():
print("Hello, World!")
def add(a, b):
return a + b
"""
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print("Function name:", node.name)🔍 How it works:
Uses
ast.walk(tree)to iterate over all nodes.Checks for
ast.FunctionDefnodes to find function definitions.
🔹 3. Counting Number of If-Statements in Code
Traverse the AST to count
ifstatements.
🔍 How it works:
Uses
sum(1 for node in ast.walk(tree) if isinstance(node, ast.If))to countifnodes.
🔹 4. Extracting All Variable Assignments
Get all variables assigned in the code.
🔍 How it works:
Looks for
ast.Assignnodes and extracts variable names.
🔹 5. Detecting Function Calls in Code
Identify all function calls in a script.
🔍 How it works:
Detects
ast.Callnodes and extracts function names.
🔹 6. Modifying AST – Changing Function Names
Rewrite function names dynamically.
🔍 How it works:
Uses
ast.NodeTransformerto rename all function definitions.
🔹 7. Executing Modified AST Code
Convert modified AST back to executable code.
🔍 How it works:
ast.unparse(tree)converts AST back to code.exec()executes the modified code.
🔹 8. Checking for Unsafe exec() Usage
exec() UsageDetects the use of
exec()in user-supplied code.
🔍 How it works:
Scans for
ast.Execnodes to detectexec()calls.
🔹 9. Extracting All Imported Modules
Find all modules imported in a script.
🔍 How it works:
Extracts all
importandfrom ... importstatements.
🔹 10. Detecting List Comprehensions
Identify list comprehensions in the code.
🔍 How it works:
Counts occurrences of
ast.ListComp, which represents list comprehensions.
Summary of AST Python Code Snippets
1️⃣
Parsing Python code into an AST
2️⃣
Extracting function names from AST
3️⃣
Counting if statements in code
4️⃣
Finding assigned variables
5️⃣
Detecting function calls
6️⃣
Modifying function names dynamically
7️⃣
Executing modified AST code
8️⃣
Checking for unsafe exec() usage
9️⃣
Extracting all imported modules
🔟
Detecting list comprehensions
🚀 Conclusion
AST (Abstract Syntax Trees) allow deep code analysis and transformations.
Python’s
astmodule provides parsing, modification, and execution of AST objects.This is useful for security checks, refactoring, and optimizations.
Last updated