Skip to content

Instantly share code, notes, and snippets.

@victory-sokolov
Created January 15, 2024 14:06
Show Gist options
  • Save victory-sokolov/b51b09c224463baca608f34f0ecd819d to your computer and use it in GitHub Desktop.
Save victory-sokolov/b51b09c224463baca608f34f0ecd819d to your computer and use it in GitHub Desktop.
Python Get exception nodes with AST
import ast
# define a sample function
def foo():
try:
x = 1 / 0
except ZeroDivisionError:
pass
# parse the function into an AST tree
tree = ast.parse(foo)
# traverse the AST tree and look for exception nodes
exceptions = []
for node in ast.walk(tree):
if isinstance(node, ast.ExceptHandler):
exceptions.append(node.type.id)
# print the list of exceptions
print(exceptions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment