Finding the line number of an 'else' statement via ast

Michael Rene Armida me at marmida.com
Fri May 11 00:35:44 EDT 2012


Given this source:

def do_something(val):
    if val:
        return 'a'
    else:
        return 'b'

How do I get the line number of the "else:" line, using the ast
module?  The grammar only includes the 'orelse' list:

    If(expr test, stmt* body, stmt* orelse)

...but 'orelse' is the list of statements under the 'else' token, not
a node representing the token itself.

I have a suspicion that this isn't possible, and shouldn't be, and the
giveaway word above was "token."  Because the tokens themselves aren't
part of the abstract syntax tree.

Here's an interactive session showing me poking around the If node:

>>> import ast
>>> tree = ast.parse('''
... if True:
...     pass
... else:
...     pass
... ''')
>>> tree.body[0].orelse
[<_ast.Pass object at 0x7f1301319390>]
>>> tree.body[0]._fields
('test', 'body', 'orelse')
>>> for i in ast.iter_child_nodes(tree.body[0]):
...     print i.__class__.__name__
...
Name
Pass
Pass


Is my suspicion correct?  Or is there a way to get the line number of
that 'else:'?



More information about the Python-list mailing list