1 回答

TA貢獻1863條經驗 獲得超2個贊
基于@Kevin 對“ ast.parse ”的建議
我可以使用
def hasRecursion(tree):
for node in [n for n in ast.walk(tree)]:
nodecls = node.__class__
nodename = nodecls.__name__
if isinstance(node, (ast.For, ast.While)):
for nodeChild in node.body:
#node.body Or ast.iter_child_nodes(node)
if isinstance(nodeChild, (ast.For, ast.While)):
return True
return False
expr="""
for i in 3:
print("first loop")
for j in i:
print("nested loop")
print('normal')
"""
tree = ast.parse(expr, mode="exec")
print(hasRecursion(tree))
添加回答
舉報