[Solved] Python regex – check String for nested loops


Based on @Kevin s suggestion with “ast.parse

I could use

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))

ast.parse code examples

Thanks @Kevin

solved Python regex – check String for nested loops