Search code examples
pythonabstract-syntax-tree

Why can't python ast detect an if statement within a function?


I am a newbie to ASTs as I come from a Statistics background. As per my observation, Python is unable to detect an if statement for the following code -

import ast
from pprint import pprint

tree = ast.parse("""
def add(a, b):
  return a + b

def subr(a,b):
    if 2>3:
        print("true")
    else:
        print("false")
    return 0
""")




for node in ast.iter_child_nodes(tree):
    print(isinstance(node, ast.If))

However, if there is no function, it can detect the if statement -

import ast
from pprint import pprint

tree = ast.parse("""
if 2>3:
    print("true")
else:
    print("false")
""")




for node in ast.iter_child_nodes(tree):
    print(isinstance(node, ast.If))


Could someone please tell me what is the problem with my former code block?


Solution

  • @Mathias R. Jessen is correct. iter_child_nodes() can only iterate through immediate child nodes. To iterate through the entire code, one should use ast.walk()