How to parse over a Python expr?
Erik Max Francis
max at alcyone.com
Fri Aug 30 22:28:53 CEST 2002
Stefan Franke wrote:
> 2. I guess any $(expr)-like string interpolation mechanism needs the
> thing. As does - in a similar fashion, restricted to string literals -
> any CSV (comma
> separated value) parser.
In empy, Python expressions are set off with the @(...) notation. In
order to pull out the expression, I walk along the substring ...,
keeping track of the depth (starting with zero) of the parentheses (an
open parenthesis increments the depth; a close parenthesis decrements
it) as I go, and ignoring any parentheses that appear inside of a string
literal. That way I know when I'm done when I hit a close parenthesis
that marks the end of the whole expression, rather than just an internal
parenthesis, when the depth drops below zero.
I then leave it up to the Python interpreter itself, via eval, to
determine whether or not the expression is valid. If all you're looking
for is a way to set off Python expressions in some embedded text
environment, that should be enough.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
Church / http://www.alcyone.com/pyos/church/
A lambda calculus explorer in Python.
More information about the Python-list