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

Terry Reedy tjreedy at udel.edu
Fri May 11 10:58:51 EDT 2012


On 5/11/2012 12:35 AM, 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.

The main reason to record line numbers in the parse tree and hence the 
CPython code object is to print the line number and corresponding line 
in exception tracebacks. Since 'else:' on a line by itself is not a 
statement in itself and does not contain an expression that could raise, 
there is no need to record a line number. So I would not be surprised if 
it is not directly recorded.

'else: 1/0' and "elif 1/0" will have recorded line numbers.

If you can get the last line of the if-block and first line of the 
else-block, and there is a gap, you might guess that the else is in 
between ;-).

-- 
Terry Jan Reedy




More information about the Python-list mailing list