英文:
Visiting a assert statement within a functiondef using Python ast
问题
这是我为您翻译的代码部分:
class TransformMe(ast.NodeTransformer):
def visit_Assert(self, node):
return None # 这里进行一些处理
def visit_FunctionDef(self, node):
for line_node in node.body:
if isinstance(line_node, ast.Assert):
line_node = ast.NodeTransformer.generic_visit(self, line_node)
for test_node in ast.walk(line_node):
# 这里进行更多处理
pass
return node
module_node = ast.parse(code)
new_module_node = TransformMe().visit(module_node)
print(ast.unparse(new_module_node))
希望这对您有所帮助。如果您有更多问题,请随时提出。
英文:
I am currently doing some code manipulation and I am unable to visit an "Assert" statement within a "FunctionDef". How I visit an internal Assert node within a Function node?
Here is a sample code I am modifying
assert True == True
def test_code():
result = 5
assert result == 5
Here is my NodeTransformer
class TransformMe(ast.NodeTransformer):
def visit_Assert(self, node):
return None # Some processing here
def visit_FunctionDef(self, node):
for line_node in node.body:
if isinstance(line_node, ast.Assert):
line_node = ast.NodeTransformer.generic_visit(self, line_node)
for test_node in ast.walk(line_node):
# More processing here
pass
return node
Processing it with
module_node = ast.parse(code)
new_module_node = TransformMe().visit(module_node)
print(ast.unparse(new_module_node))
Current output is
def test_code():
result = 5
assert result == 5
But the output I want is
def test_code():
result = 5
How do I make this work? How do I visit and process an internal Assert node?
答案1
得分: 0
感谢 @mkrieger1 的评论,这里是工作的NodeTransformer。
class TransformMe(ast.NodeTransformer):
def visit_Assert(self, node):
return None # 这里进行一些处理
def visit_FunctionDef(self, node):
i = len(node.body) - 1
while i >= 0:
line_node = node.body[i]
if isinstance(line_node, ast.Assert):
line_node = self.visit_Assert(line_node)
if line_node is None:
del node.body[i]
i -= 1
continue
else:
for test_node in ast.walk(line_node):
# 这里进行更多处理
pass
i -= 1
return node
英文:
Thanks to @mkrieger1 's comment, there is the working NodeTransformer.
class TransformMe(ast.NodeTransformer):
def visit_Assert(self, node):
return None # Some processing here
def visit_FunctionDef(self, node):
i = len(node.body) - 1
while i >= 0:
line_node = node.body[i]
if isinstance(line_node, ast.Assert):
line_node = self.visit_Assert(line_node)
if line_node is None:
del node.body[i]
i -= 1
continue
else:
for test_node in ast.walk(line_node):
# More processing here
pass
i -= 1
return node
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论