Limited Evaluator (leval)

1.3.0 · active · verified Thu Apr 16

leval is a Python library that provides a safe and limited evaluator for untrusted Python expressions, aiming to prevent arbitrary code execution while allowing controlled calculations. It is currently at version 1.3.0 and actively maintained, with recent updates focusing on feature enhancements and internal improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `leval.simple.evaluate` for evaluating expressions with provided context, including basic arithmetic, string manipulation, and conditional logic. It also highlights the `loose_is_is_not` parameter for controlling identity operator behavior introduced in version 1.2.0.

from leval.simple import evaluate

# Basic evaluation with context
expression_1 = "x * (y + 2)"
context_1 = {"x": 5, "y": 3}
result_1 = evaluate(expression_1, **context_1)
print(f"'{expression_1}' with context {context_1} evaluates to: {result_1}")

# Evaluation with string methods and built-in functions
expression_2 = "s.upper() + ' WORLD!' if len(s) > 5 else s.lower()"
context_2 = {"s": "hello"}
result_2 = evaluate(expression_2, **context_2)
print(f"'{expression_2}' with context {context_2} evaluates to: {result_2}")

# Explicitly opting out of loose 'is/is not' behavior introduced in v1.2.0
# For example, '0 is False' would evaluate to True with default 'loose_is_is_not=True'
expression_3 = "my_value is None"
context_3 = {"my_value": 0}
result_3_loose = evaluate(expression_3, **context_3)
result_3_strict = evaluate(expression_3, loose_is_is_not=False, **context_3)
print(f"'{expression_3}' (0 is None) with loose_is_is_not (default): {result_3_loose}")
print(f"'{expression_3}' (0 is None) with loose_is_is_not=False: {result_3_strict}")

view raw JSON →