206. AST (Abstract Syntax Trees) in Python
🔹 1. Parsing Python Code into an AST
import ast
code = "x = 5 + 3"
tree = ast.parse(code)
print(ast.dump(tree, indent=4))🔹 2. Extracting Function Names from Python Code
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)🔹 3. Counting Number of If-Statements in Code
🔹 4. Extracting All Variable Assignments
🔹 5. Detecting Function Calls in Code
🔹 6. Modifying AST – Changing Function Names
🔹 7. Executing Modified AST Code
🔹 8. Checking for Unsafe exec() Usage
exec() Usage🔹 9. Extracting All Imported Modules
🔹 10. Detecting List Comprehensions
Summary of AST Python Code Snippets
Snippet
Description
🚀 Conclusion
Last updated