我是 LibCST 的新手。我正在编写一个工具而不是修改代码。我想将一个 elif (orelse=If) 添加到现有的 If elif else 节点。简单的例子:
# before
if data == "a":
execute_a(data)
elif data == "b":
execute_b(data)
else:
raise RuntimeError("switch not recognized")
#after
if data == "a":
execute_a(data)
elif data == "inserted":
execute_inserted(data)
elif data == "b":
execute_b(data)
else:
raise RuntimeError("switch not recognized")
我的代码如下所示:
def leave_Try(self, node: cst.Try, updated_node: cst.Try):
# we now have enough information to make the insertion
if self.in_dispatcher:
self.in_dispatcher = False
# first let's generate a new if
new_if_str = build_command_str("New_Intent", "New_command")
new_if = cst.parse_module(new_if_str).code
#new_if is a module not an if, we may need to modify it.
# now lets make last_if point to the new
self.last_if.orelse = new_if
#and the new_ifs orelse point to the else
new_if.orelse = self.else_if
# I am not sure what to call with the with_changes()
return node
当我执行我得到的代码时:
Exception: Expected a node of type CSTNode or a RemovalSentinel, but got a return value of NoneType
我不确定是否感到惊讶,因为我没有正确更新。我觉得 Try 块是错误的地方。我做错了什么。我将不胜感激任何见解。
谢谢,安德鲁