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

Mark Lawrence breamoreboy at yahoo.co.uk
Fri May 11 06:43:55 EDT 2012


On 11/05/2012 05:35, Michael Rene Armida wrote:
> 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:'?

Get the line number of the first pass and add one?

-- 
Cheers.

Mark Lawrence.




More information about the Python-list mailing list