I am trying to replace print
with raise ValueError
. But this program returns only TypeError: expected some sort of expr, but got <ast.Raise object at 0x000001DF779469A0>
. How do I fix the following code to achieve my goal?
import ast
class MyVisitor(ast.NodeTransformer):
def visit_Name(self, node: ast.Name):
if node.id == 'print':
result = ast.parse("raise ValueError").body[0]
result.lineno = node.lineno
result.col_offset = node.col_offset
return result
return node
program = """
f = 4 + 4
print("sth")
"""
tree = ast.parse(program)
my_visitor = MyVisitor()
tree = my_visitor.visit(tree)
code = compile(ast.fix_missing_locations(tree), "filename", "exec")
exec(code)
Visiting the Expr
nodes instead, you can replace the print statement
with a raise valueError
statement:
import ast
class MyVisitor(ast.NodeTransformer):
def visit_Expr(self, node: ast.Expr):
print(f"{node.__class__ =}")
if node.__class__ != ast.Expr:
return node
if node.value.__class__ != ast.Call:
return node
if node.value.func.id == 'print':
result = ast.parse("raise ValueError").body[0]
result.lineno = node.lineno
result.col_offset = node.col_offset
return result
return node
program = """
f = 4 + 4
print("sth")
"""
tree = ast.parse(program)
atv_out = ast.dump(tree)
my_visitor = MyVisitor()
tree = my_visitor.visit(tree)
code = compile(ast.fix_missing_locations(tree), "filename", "exec")
exec(code)
# raises ValueError