[Tutor] bracket issue

Danny Yoo dyoo at hashcollision.org
Mon Apr 17 13:42:14 EDT 2017


> coming to recursion well i currently use eval() so everything ok i don't
> have to worry about brackets but i want to write my own parser. a top down
> parser for expressions.


Do *not* use eval to parse expressions.  It is an extremely bad idea to do this.


Instead, you can use ast.parse, which will give you the parse tree
directly.  It uses the grammatical structure described in:

    https://docs.python.org/2/library/ast.html#abstract-grammar


Example:

##############################################################
>>> tree = ast.parse("2*3+3(8-4(5+6+9))+2+3+3(4/4)", mode='eval')
>>> tree
<_ast.Expression object at 0x7f86c447e490>
>>> tree.body
<_ast.BinOp object at 0x7f86c447e450>
>>> tree.body.op
<_ast.Add object at 0x7f86c4487cd0>
>>> tree.body.left
<_ast.BinOp object at 0x7f86c447e390>
>>>
>>> tree.body.left.left.left.left.left
<_ast.Num object at 0x7f86c440ed90>
>>> tree.body.left.left.left.left.left.n
2
>>> tree.body.left.left.left.left.right.n
3
>>> tree.body.left.left.left.left.op
<_ast.Mult object at 0x7f86c4487dd0>
##############################################################

The example shows that we can navigate the structure of the expression
to get at individual nodes.  Because the structure is recursive,
you'll likely be writing recursive functions that do case-analysis on
the 'expr' type described in the abstract grammar.


To get at the "3(8-4(5+6+9))" part of the example expression, we take
a right instead of a left.  We get back a "Call" object,


###################################
>>> tree.body.left.left.left.right
<_ast.Call object at 0x7f86c440ee10>
###################################


which according to the grammar, has a "func" and "args", themselves
being expressions.


###################################
>>> tree.body.left.left.left.right.func
<_ast.Num object at 0x7f86c440ee50>
>>> tree.body.left.left.left.right.func.n
3
>>> tree.body.left.left.left.right.args
[<_ast.BinOp object at 0x7f86c440ee90>]
###################################


I hope this helps to give you a brief overview on navigating the
abstract syntax tree.  Good luck!


More information about the Tutor mailing list