Created
January 15, 2024 14:06
-
-
Save victory-sokolov/b51b09c224463baca608f34f0ecd819d to your computer and use it in GitHub Desktop.
Python Get exception nodes with AST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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