DEV Community

Yaroslav Polyakov
Yaroslav Polyakov

Posted on

evalidate: secure eval() for python

Evalidate is python module for safe eval()'uating user-supplied (possible malicious) logical expressions in python syntax.

Install: pip3 install evalidate

Usage:

from evalidate import safeeval, EvalException

src="a+b" # source code
# src="__import__('os').system('clear')"
c={'a': 1, 'b': 2} # context, variables which will be available for code

try:
    result = safeeval(src,c)
    print(result)
except EvalException as e:
    print("ERR:", e)
Enter fullscreen mode Exit fullscreen mode

Gives output:

3
In case of dangerous code src="__import__('os').system('clear')"
output will be: ERR: Operation type Call is not allowed

Evalidate can be easily configured to allow/restrict special function calls (e.g. allow int() function, but not os.system())

If compare to asteval (which is actually has much more features), evalidate is much faster in my benchmarks (benchmark code in repo): 0.017s vs 1.232s

Git repo: https://github.com/yaroslaff/evalidate

Top comments (0)