I'm working on a program that takes in user input which often includes things like math.sqrt(), imaginary numbers, multiplication, division, and similar (basically, standard math plus imaginary numbers).

Currently, I'm using eval() (don't worry, this is not the sort of program that is used on public computers and I have a major warning on the github repository) but I want to switch this to some sort of custom parser that can handle calls to the cmath and math modules, along with *, /, +, and - without risking computer security.

I've heard of ast, but it also seems like a significant amount of work, and sandboxing eval() is very difficult to impossible. What are my options for approaches here?


If you really want to parse the user's input, you could have a look at the Lark library.

It has an intuitive syntax for defining EBNF grammar with callback functions. The documentation is pretty good and one of the tutorial example is basically what you want.

On the other hand, if you do trust your user so much, why not just use the path to a python script to import as an input?


If you want to execute user-input without giving the user the chance to mess with the computer, there are only a few options

  1. Allow the user to enter python code and pass that through to a sandboxed eval
  2. Design your own mini-language (DSL; Domain Specific Language) and create a parser and interpreter for it.
  3. Search the internet for an existing DSL that matches your requirements and re-use that.

None of the options is really easy to achieve, but at least for option 2 there are tools available (for example as referenced in the answer by @AlexisPrel) that can do a lot of the grunt work for you.


Take a look at Crafting Interpreters.

The later part about a Byte-Code interpreter is still being written but the basics of how languages are composed, and how to write a parser and interpreter are complete - and easy to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.