loki locus loki locus - 1 month ago 23
Python Question

rename elif in python

I was recently playing a bit around with adding some optional statement names in python and that worked fine until i got to the if statement and I added an optional name for else and elif:

if_stmt = 'if' test ':' suite ('elif' test ':'suite)* ['else' ':' suite] | 'wenn' test ':' suite ('andernfalls' test ':'suite)* ['sonst' ':' suite]


then it compiled without errors, but when I ran a test with wenn and andernfalls and the Interpreter threw the error:

SystemError: unexpected token in 'if' statement: andernfalls


And every other Addition I made worked great. So why can´t I add other else and elif and how could I do?

I´m modifying the most recent python 2.7 code from the python website

EDIT
My test code is:

x = 1
y = 2
wenn x > y:
print 1
andernfalls x < y:
print 2
sonst:
print 3


The file i was adding the line at the top to was the Grammar file in the Grammar directory of the python source code

Answer Source

else and elif have some special-case handling inside the AST generation code:

static stmt_ty
ast_for_if_stmt(struct compiling *c, const node *n)
{
    ...
    /* s[2], the third character in the string, will be
       's' for el_s_e, or
       'i' for el_i_f
    */
    if (s[2] == 's') {
        ...
    }
    else if (s[2] == 'i') {
        ...

You'll have to modify ast_for_if_stmt in Python/ast.c to change that handling.