[issue44177] Unable to get the else while parsing through AST module

Eric V. Smith report at bugs.python.org
Wed May 19 07:31:16 EDT 2021


Eric V. Smith <eric at trueblade.com> added the comment:

Formatting the result, I get:
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=[])

You'll have to extract the "else" part by walking the tree yourself.

> I was parsing python file using AST module but ran into a situation where the else statement is not found in the parsed data.

It is in the parsed data, though. Just not directly in the "If" node.

----------
nosy: +eric.smith

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44177>
_______________________________________


More information about the Python-bugs-list mailing list