Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it possible to opt-out from loose is/is-not operations #12

Merged
merged 1 commit into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion leval/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def __init__(
max_time: Optional[float] = None,
allowed_constant_types: Optional[Iterable[type]] = None,
allowed_container_types: Optional[Iterable[type]] = None,
loose_is_operator: bool = True,
):
"""
Initialize an evaluator with access to the given evaluation universe.
Expand All @@ -62,6 +63,7 @@ def __init__(
self.universe = universe
self.max_depth = _default_if_none(max_depth, self.default_max_depth)
self.max_time = float(max_time or 0)
self.loose_is_operator = bool(loose_is_operator)
self.allowed_constant_types = frozenset(
_default_if_none(
allowed_constant_types,
Expand Down Expand Up @@ -123,7 +125,7 @@ def visit_Compare(self, node): # noqa: D102
if len(node.ops) != 1:
raise InvalidOperation("Only simple comparisons are supported", node=node)
op = node.ops[0]
if isinstance(op, (ast.Is, ast.IsNot)):
if self.loose_is_operator and isinstance(op, (ast.Is, ast.IsNot)):
left = self._visit_or_none(node.left)
right = self._visit_or_none(node.comparators[0])
else:
Expand Down
8 changes: 8 additions & 0 deletions leval_tests/test_leval.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,11 @@ def test_readme_example():
assert simple_eval("x < -80 or x > 125 or x == 85", values={"x": 85})
assert simple_eval("abs(x) > 80", values={"x": -85}, functions={"abs": abs})
assert simple_eval("x.y.z + 8", values={("x", "y", "z"): 34}) == 42


def test_strict_is():
evaluator = Evaluator(EvaluationUniverse(), loose_is_operator=False)
with pytest.raises(NoSuchValue):
assert evaluator.evaluate_expression("a is b")
with pytest.raises(NoSuchValue):
assert evaluator.evaluate_expression("a is not b")