Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matthewdeanmartin/fa88ae03818a5a8e503c8685b97234b1 to your computer and use it in GitHub Desktop.
Save matthewdeanmartin/fa88ae03818a5a8e503c8685b97234b1 to your computer and use it in GitHub Desktop.
errors? not if you ignore them
import ast
import inspect
import types
from functools import wraps
def try_except_pass_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Get the function's source code
# source_code = func.__code__.co_code
source_code = inspect.getsource(func)
source_ast = ast.parse(source_code)
# Define a function that wraps a try-except-pass block around a given node
def wrap_with_try_except_pass(node):
# Create a try-except-pass block around the node
try_except_pass = ast.Try(
body=[node],
handlers=[
ast.ExceptHandler(
type=ast.Name(id="Exception", ctx=ast.Load()),
name=None,
body=[ast.Pass()]
)
],
orelse=[],
finalbody=[]
)
return try_except_pass
# Traverse the AST and replace each statement with a try-except-pass block
for node in ast.walk(source_ast):
if isinstance(node, ast.stmt):
try_except_pass = wrap_with_try_except_pass(node)
ast.copy_location(try_except_pass, node)
ast.fix_missing_locations(try_except_pass)
for n in ast.walk(source_ast):
print(n, isinstance(n, ast.stmt))
if hasattr(n, "body"):
print(" " + str(n.body))
#isinstance(n, ast.expr)
parent_node = next((n for n in ast.walk(source_ast) if hasattr(n, "body") and n.body == [node]), None)
if parent_node is not None:
index = parent_node.body.index(node)
parent_node.body[index] = try_except_pass
# Compile the modified AST into a code object
code = compile(source_ast, filename="<ast>", mode="exec")
# Create a new function from the modified code object
new_func = types.FunctionType(code, func.__globals__, func.__name__, func.__defaults__, func.__closure__)
# Call the new function
return new_func(*args, **kwargs)
return wrapper
@try_except_pass_decorator
def cannot_stop_the_code():
print("Hello World!")
print(1/0)
print("Goodbye World, don't let an Exception ruin your day")
return 6
if __name__ == '__main__':
cannot_stop_the_code()
@matthewdeanmartin
Copy link
Author

#chatGPT wrote this with some debugging from me. Currently fails to modify/wrap statement nodes with try/except/pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment