Skip to content

Commit

Permalink
Merge pull request #13 from valohai/none-is-followup
Browse files Browse the repository at this point in the history
Invalid attribute exception subclass
  • Loading branch information
memona008 authored Dec 29, 2023
2 parents 5b9d6b7 + bf0a746 commit 78a6c80
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 4 deletions.
7 changes: 6 additions & 1 deletion leval/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@

DEFAULT_ALLOWED_CONTAINER_TYPES = frozenset((tuple, set))
DEFAULT_ALLOWED_CONSTANT_TYPES = frozenset(
(str, int, float, NoneType),
(
str,
int, # NB: this implicitly includes bool
float,
NoneType,
),
)


Expand Down
4 changes: 4 additions & 0 deletions leval/excs.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ class InvalidOperands(InvalidOperation):
pass


class InvalidAttribute(InvalidOperation):
pass


class NoSuchValue(NameError, EvaluatorError):
pass

Expand Down
9 changes: 7 additions & 2 deletions leval/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ast
from typing import Tuple

from leval.excs import InvalidOperation
from leval.excs import InvalidAttribute


def expand_name(node: ast.Attribute) -> Tuple[str, ...]:
Expand All @@ -18,8 +18,13 @@ def walk_attr(kid):
walk_attr(kid.value)
elif isinstance(kid, ast.Name):
attr_bits.append(kid.id)
elif isinstance(kid, ast.Constant):
raise InvalidAttribute(
f"Accessing attributes of constants ({kid}) is not allowed",
node=node,
)
else:
raise InvalidOperation( # pragma: no cover
raise InvalidAttribute( # pragma: no cover
f"Unsupported attribute structure in {node}",
node=node,
)
Expand Down
6 changes: 5 additions & 1 deletion leval_tests/test_leval.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from leval.evaluator import Evaluator
from leval.excs import (
InvalidAttribute,
InvalidOperands,
InvalidOperation,
NoSuchFunction,
Expand Down Expand Up @@ -81,7 +82,10 @@
),
("Can't access weird methods off valid names", "abs.__class__", NoSuchValue),
("Arbitrary Python code is not allowed", "if x > a:\n hello()", SyntaxError),
("Can't access attributes off constants", "(3).__class__", InvalidOperation),
("Can't access numeric constants' attributes", "(3).__class__", InvalidAttribute),
("Can't access Nones' attributes", "None.__class__", InvalidAttribute),
("Can't access Falses' attributes", "False.__class__", InvalidAttribute),
("Can't access Trues' attributes", "True.__class__", InvalidAttribute),
(
"Walruses aren't allowed",
"(a := 3) + 8",
Expand Down

0 comments on commit 78a6c80

Please sign in to comment.