Learn to Code via Tutorials on Repl.it!

← Back to all posts
Evaln't: How to replace `eval` in your code
CodeLongAndPros (1624)

Why you should never use eval

Some of you out there will know the dangers of the eval function, and some of you will not.

eval is (in)famously used in calculators and the such.

For example:

print("=== Magic math == ")

print(eval(input("Math here: ")))

You can then, for example, get a bash shell:

I'm going to go over the three ways to not use eval.

They are:

  • Write a parser
  • ast.literal_eval
  • asteval

#1: Write a parser.

This one is the hardest, but if you are using an embedded language, this one is the best option.

For more info, see CSharpIsGud's tutorial

#2: Use ast.literal_eval()

This one is used when you input a value and want to parse it into data.

This is not really used much, but here's an example:

import ast

di = input("Enter a list: ")

li = ast.literal_eval(di)

print(li, type(li))

You can always cast to the type you want, but when the data type can vary...

#3: Use asteval.

This one is the best.

Asteval is a third-party package that implements Python, removing the stblibs and __import__()

Let's rework our math calculator above:

from asteval import Interpreter
eval = Interpreter()

print("=== More Magic Math ===")

print(eval(input("More Math: ")))

If I try the same exploit as above, we get this:

And if I try another exploit:

As you can see, the asteval module is great for evaluating math, and it also protects you from code injection.

Well, that's all on the topic of eval. Thanks!