How to Write a Simple Math Interpreter in Python
<p>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 <code>2 + 3</code>, support context to use variables: <code>apples + 2 * oranges</code>, and parentheses: <code>(2 + 3) - apples</code>.</p>
<p>The obvious (and least appropriate) solution was to use <code>eval</code>. This standard function takes a string and runs it, treating it like Python code. This is considered to be very unsafe: <code>eval</code> 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.</p>