Skip to content

Commit

Permalink
fix: Raise exception when attempting to look up non-existent variable…
Browse files Browse the repository at this point in the history
… name.
  • Loading branch information
matthewwardrop committed Oct 4, 2023
1 parent 91bdd5d commit 2f0a480
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions formulaic/materializers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
if TYPE_CHECKING: # pragma: no cover
from formulaic import FormulaSpec, ModelSpec, ModelSpecs


EncodedTermStructure = namedtuple(
"EncodedTermStructure", ("term", "scoped_terms", "columns")
)
Expand Down Expand Up @@ -590,7 +589,12 @@ def _evaluate_factor(
return self.factor_cache[factor.expr]

def _lookup(self, name: str) -> Tuple[Any, Set[Variable]]:
values, layer = self.layered_context.get_with_layer_name(name)
sentinel = object()
values, layer = self.layered_context.get_with_layer_name(name, default=sentinel)
if values is sentinel:
raise NameError(
f"`{name}` is not present in the dataset or evaluation context."
)
return values, {Variable(name, roles=("value",), source=layer)}

def _evaluate(
Expand Down
17 changes: 17 additions & 0 deletions tests/materializers/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,3 +455,20 @@ def test_quoted_python_args(self):
assert mm.shape == (3, 2)
assert len(mm.model_spec.structure) == 2
assert numpy.all(mm.values == numpy.array([[1, 1], [1, 4], [1, 9]]))

def test_lookup_nonexistent_variable(self):
data = pandas.DataFrame({})
with pytest.raises(
FactorEvaluationError,
match=re.escape(
"Unable to evaluate factor `a`. [NameError: `a` is not present in the dataset or evaluation context.]"
),
):
PandasMaterializer(data).get_model_matrix("a")
with pytest.raises(
FactorEvaluationError,
match=re.escape(
"Unable to evaluate factor `I(a)`. [NameError: name 'a' is not defined]"
),
):
PandasMaterializer(data).get_model_matrix("I(a)")

0 comments on commit 2f0a480

Please sign in to comment.