| Crates.io | pyisheval |
| lib.rs | pyisheval |
| version | 0.9.0 |
| created_at | 2024-12-12 15:48:28.321489+00 |
| updated_at | 2024-12-24 05:19:47.179014+00 |
| description | A Python-like expression evaluator in Rust |
| homepage | |
| repository | https://github.com/neka-nat/pyisheval |
| max_upload_size | |
| id | 1481369 |
| size | 125,536 |
pyisheval is a Rust library that allows you to evaluate Python-like expressions.
It's not a full Python interpreter, but it supports a subset of Python-like syntax:
+, -, *, /, //, %, **, >, <, >=, <=, ==, !=lambda x: x + 1)abs, max, min, int, float, len, sum, str, dict, list, tuple, set, etc.[y * 2 for y in x]x if x > 5 else 0str.upper(), str.lower(), str.splitlines(), etc.list.append(), list.clear(), etc.dict.clear(), dict.get(), dict.items(), dict.keys(), dict.values(), etc.No classes, functions (def), or control structures are supported.
cargo add pyisheval
use pyisheval::Interpreter;
fn main() {
let mut interp = Interpreter::new();
// Assign variables
interp.eval("x = 10").unwrap();
interp.eval("y = 20").unwrap();
// Arithmetic
let val = interp.eval("x + y * 2").unwrap();
println!("{}", val); // 50
// Lambda
interp.eval("inc = lambda a: a + 1").unwrap();
let val = interp.eval("inc(x)").unwrap();
println!("{}", val); // 11
// Conditional expression
let val = interp.eval("x if x > y else y").unwrap();
println!("{}", val); // 10
// List comprehension
let val = interp.eval("[y * 2 for y in x]").unwrap();
println!("{}", val); // [2, 4, 6, 8, 10]
// Dict comprehension
let val = interp.eval("{y: y * 2 for y in x}").unwrap();
println!("{}", val); // {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
// String method
let val = interp.eval("'hello'.upper()").unwrap();
println!("{}", val); // HELLO
// List method
interp.eval("x = [1, 2, 3]").unwrap();
let val = interp.eval("x.append(4)").unwrap();
println!("{}", val); // [1, 2, 3, 4]
// Dict method
interp.eval("x = {'a': 1, 'b': 2}").unwrap();
let val = interp.eval("x.items()").unwrap();
println!("{}", val); // [(a, 1), (b, 2)]
}
This library aims to provide a lightweight and embedded Python-like expression evaluator for scenarios where you want to let users provide arithmetic expressions or simple lambdas without embedding a full Python interpreter.