Message393941
Hi Team,
I was parsing python file using AST module but ran into a situation where the else statement is not found in the parsed data.
---------------------
Module used is: ast
---------------------
In the parsed data I can see "if" followed by "elif" but the "else" part I am not able to see.
Sample code used:
---------------------
sample_data = """
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
"""
---------------------
tree = ast.parse(sample_data )
The above code provide me below data in ast.dump(tree)
Module(body=[If(test=Compare(left=Name(id='num', ctx=Load()), ops=[Gt()], comparators=[Constant(value=0, kind=None)]), body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Constant(value='Positive number', kind=None)], keywords=[]))], orelse=[If(test=Compare(left=Name(id='num', ctx=Load()), ops=[Eq()], comparators=[Constant(value=0, kind=None)]), body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Constant(value='Zero', kind=None)], keywords=[]))], orelse=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Constant(value='Negative number', kind=None)], keywords=[]))])])], type_ignores=[])
While I was traversing through this tree I can't see else in the structure because it is subpart of orelse i.e. inside elif part.
Doc referred is : https://docs.python.org/3/library/ast.html
Thanks and Best Regards,
Bikram |
|
Date |
User |
Action |
Args |
2021-05-19 09:49:02 | bikrammehra97 | set | recipients:
+ bikrammehra97, lys.nikolaou, pablogsal |
2021-05-19 09:49:02 | bikrammehra97 | set | messageid: <1621417742.65.0.783924257321.issue44177@roundup.psfhosted.org> |
2021-05-19 09:49:02 | bikrammehra97 | link | issue44177 messages |
2021-05-19 09:49:02 | bikrammehra97 | create | |
|