Skip to content

Instantly share code, notes, and snippets.

@MyNameIsTrez
Created November 20, 2025 20:28
Show Gist options
  • Select an option

  • Save MyNameIsTrez/625738977a28fe7814bc454dc5ad9b80 to your computer and use it in GitHub Desktop.

Select an option

Save MyNameIsTrez/625738977a28fe7814bc454dc5ad9b80 to your computer and use it in GitHub Desktop.
# Reads foo.py, and prints the names of classes and methods inside of it.
import ast
def extract_structure(file_path):
with open(file_path, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=file_path)
structure = []
for node in tree.body: # Only top-level nodes
if isinstance(node, ast.ClassDef):
structure.append(f"Class: {node.name}")
for item in node.body:
if isinstance(item, ast.FunctionDef):
structure.append(f" Method: {item.name}")
elif isinstance(node, ast.FunctionDef):
structure.append(f"Function: {node.name}")
return structure
# Example usage:
file_path = "foo.py"
for line in extract_structure(file_path):
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment