Python Forum

Full Version: python ast if-elif confusion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm working with the python ast and have a question regarding difference between how different else conditions are handled. I'm finding that an elif statement and else: followed by a subsequent are stored in the same manner as part of the syntax tree.

Original Code:
a = 0
b = 0
c = 0
if a == 0:
    b = 1  
elif a == 1:
    b = 2
else:
  if c == 0:
      b = 3
  else:
      b = 4
I'm assuming this is the case because these statements are logically equivalent, so when the AST is actually processed by the python interpreter it views them as the same.
The reason I'm asking this is I'm building a code translator which takes simple procedural statements and translates them to a variety of languages, so I'd like to get the resulting code as close to the python source as possible. For example, if I were to re-translate the python AST back into python it would then look like:

XLT'd code
a = 0
b = 0
c = 0
if a == 0:
    b = 1  
elif a == 1:
    b = 2
elif c == 0:
     b = 3
else:
     b = 4
Note that the last else branch got modified in the above. Looking at the syntax tree for the original code, the if statemnet looks something like this:

Output:
If (a == 0) Body -> Assign(b = 1) Orelse -> If (a == 1) -> Body -> Assign(b = 2) -> Orelse -> If (c == 0) -> Body -> Assign(b = 3) -> Orelse -> Assign(b = 4)
Anyway, the root of my issue is that elif and else->if statements look the same in the sytnax tree which results in my translation code handling them in the same manner and translating them to code which isn't exactly the same as the source.

Basically I'm handling it if I see only 1 'If' node within an orelse statement, I treat it as an 'elif' statement. If there is more than one statement (assign or if), then it writes a 'if' statement.

Am I missing something from the syntax tree which would differentiate these statements?

Note I've been using https://python-ast-explorer.com/ to view the AST for the code.

Thanks!
In the first code, if the value of a is not 0 or 1 then it moves on to check c, and b gets the following assigned value
As far as I can see the first code has the same result as the second code.
(Apr-18-2020, 12:11 PM)ibreeden Wrote: [ -> ]As far as I can see the first code has the same result as the second code.
Yes, you are right. My bad