Hi, I'm ThadeusB.

I code stuff. I raise bees. I game.

Safe Calculator In Python

So lets build a calculator in python. I wanted something similar to my old SeQyCalc program I wrote in java so many years ago. How about eval? It's built into python and makes our program just a few lines long! Wrong. Eval is bad, very bad. Read about how bad eval is.

The correct way to implement a calculator in any programming language, is to really implement a compliler/parser. SeQyCalc has a very verbose and ugly parser, but hey it worked. I followed along with effbot:simple-top-down-parsing. which has a great walkthrough about implementing a top down parser that is based off of a paper by Vaughan Pratt. I thought this method of parsing quite similar to what I implemented in SeQyCalc.

I wanted to re-structure the code that Fredrik wrote with his tutorial to use classes (ie: thread safe, contained globals, etc). I also wanted to support a little more than the basic operators, but not everything in python. The biggest thing I wanted was the ability to do named lookups from a provided dictionary as context. This way an expression could be parser.parse("value+3", value=1) == 4.

Also the code provided by Fredrik in the later examples does not actually perform any of the calculations, so I needed to add those in.

SafeCalc on github.