Py-Expression-Eval

0.3.14 · active · verified Thu Apr 16

Py-expression-eval is a lightweight Python library designed for evaluating mathematical and logical expressions from strings. It supports variables, custom functions, and a wide range of operators, making it suitable for dynamic calculation needs. The current version is 0.3.14. Releases are typically infrequent, focused on bug fixes and minor feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the parser, evaluate expressions with variables, use built-in functions, and leverage conditional operators. The `parse()` method returns an expression object which then can be evaluated with an optional dictionary of variables.

from py_expression_eval import Parser

# Initialize the parser
parser = Parser()

# Evaluate a simple expression with variables
expression1 = "2 * x + y"
variables1 = {"x": 3, "y": 5}
result1 = parser.parse(expression1).evaluate(variables1)
print(f"'{expression1}' with {variables1} evaluates to: {result1}")

# Evaluate an expression with built-in functions
expression2 = "sqrt(16) + abs(-10)"
result2 = parser.parse(expression2).evaluate()
print(f"'{expression2}' evaluates to: {result2}")

# Evaluate an expression with a conditional operator (requires v0.3.10+ for 'in')
expression3 = "x in [1, 2, 3] ? 'present' : 'absent'"
variables3 = {"x": 2}
result3 = parser.parse(expression3).evaluate(variables3)
print(f"'{expression3}' with {variables3} evaluates to: '{result3}'")

view raw JSON →