我正在编写一个生成器函数,它递归地遍历给定 astroid 节点的所有子节点。
在下面的示例中,node
是一个 astroidfunctiondef
节点。
node.getchildren()
返回节点中包含子节点的生成器。
我的目标是产生包含的每个节点。(即使在子节点中)
def recursive_walk(node):
try:
for subnode in list(node.get_children()):
# yield subnode
print(subnode)
recursive_walk(subnode)
except AttributeError:
# yield node
print(node)
except TypeError:
# yield node
print(node)
在这里,如果我已经注释掉了 yield 语句。对于打印语句,我得到了我想要的结果,但是如果我产生节点,我没有得到想要的输出。
为了重现这个: - 安装 astroid
import astroid
node = astroid.extract_node('''
def test_function(something): #@
"""Test function for getting subnodes"""
assign_line = "String"
ctx = len(assign_line)
if ctx > 0:
if ctx == 1:
return 1
if ctx > 10:
return "Ten"
else:
return 0
''')