all Python 3astterm
ast.If
control flow
The node for an if statement: test is the condition, body the branch's statements, orelse the else statements (or a nested If for elif).
Syntax
ast.If(test, body, orelse)
There is no Elif node: 'if a: … elif b: … else: …' gives an If whose orelse is a one-element list holding another If with its own orelse. Tree depth therefore grows with every elif, and counting branches means recursing through orelse. An empty orelse is an empty list, not None. The expression 'a if c else b' is a different node, IfExp.
Examples
import ast
src = 'if a:\n x = 1\nelif b:\n x = 2\nelse:\n x = 3'
node = ast.parse(src).body[0]
print(type(node).__name__, node.test.id) # → If a
inner = node.orelse[0]
print(type(inner).__name__, inner.test.id, len(inner.orelse)) # → If b 1
print(ast.parse('if a: pass').body[0].orelse) # → []
See also
Open in the full glossarydocs.python.orgReport an inaccuracy