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

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

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

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay