DEV Community

Yaroslav Polyakov
Yaroslav Polyakov

Posted on

1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs