How to write a simple math interpreter in Python

Not long ago, I had to write a certain feature for my project. It involved parsing a mathematical expression from plaintext and evaluating it. This feature had to work with basic numerical expressions like 2 + 3, support context to use variables: apples + 2 * oranges, and parentheses: (2 + 3) - apples.

The obvious (and least appropriate) solution was to use eval. This standard function takes a string and runs it, treating it like Python code. This is considered to be very unsafe: eval an execute arbitrary code, which makes it a potential security risk, especially if the input comes from untrusted sources. Malicious users could inject harmful code that could lead to unintended consequences, such as executing system commands or accessing sensitive information.

In this article, I will walk you through my safe and extensible implementation using Python’s ast module.

read more “How to write a simple math interpreter in Python”