PyTree makes it easy to learn about and experiment with the parser. To determine the
tree shape produced for a given expression, start PyTree, click on its Parser radio button,
type the expression in the input field at the bottom right, and press “input” (or your
Enter key). The parser class is run to generate a tree from your input, and the GUI
displays the result. Depending on the operators used within an expression, some very
differently shaped trees yield the same result when evaluated.
Try running PyTree on your computer to get a better feel for the parsing process. (I’d
like to show more example trees, but I ran out of page real estate at this point in the
book.)
Parsers Versus Python
The handcoded custom parser programs we’ve met in this section illustrate some in-
teresting concepts and underscore the power of Python for general-purpose program-
ming. Depending on your job description, they may also be typical of the sort of thing
you’d write regularly in a traditional language such as C. Parsers are an important
component in a wide variety of applications, but in some cases, they’re not as necessary
as you might think. Let me explain why.
So far, we started with an expression parser and added a parse tree interpreter to make
the code easier to modify. As is, the parser works, but it may be slow compared to a C
implementation. If the parser is used frequently, we could speed it up by moving parts
to C extension modules. For instance, the scanner might be moved to C initially, since
it’s often called from the parser. Ultimately, we might add components to the grammar
that allow expressions to access application-specific variables and functions.
All of these steps constitute good engineering. But depending on your application, this
approach may not be the best one in Python. Often the easiest way to evaluate input
expressions in Python is to let Python do it for us, by calling its eval built-in function.
In fact, we can usually replace the entire expression evaluation program with this one
function call. The next section will show how this can be used to simplify language-
based systems in general.
More important, the next section underscores a core idea behind the language: if you
already have an extensible, embeddable, high-level language system, why invent an-
other? Python itself can often satisfy language-based component needs.
PyCalc: A Calculator Program/Object
To wrap up this chapter, I’m going to show you a practical application for some of the
parsing technology introduced in the preceding section. This section presents PyCalc,
a Python calculator program with a graphical interface, similar to the calculator pro-
grams available on most window systems. Like most of the GUI examples in this book,
though, PyCalc offers a few advantages over existing calculators. Because PyCalc is
PyCalc: A Calculator Program/Object | 1457