Skip to content

Commit a0b026f

Browse files
committed
BREAKING CHANGE: remove CoreEntity.check_variable_defined_for_entity
The feature is still provided by `CoreEntity.get_variable` when passed the optional positional or keyword argument `check_existence`. In fact, the removed method was duplicating and already existing behaviour.
1 parent 8f04683 commit a0b026f

File tree

7 files changed

+39
-104
lines changed

7 files changed

+39
-104
lines changed

openfisca_core/entities/_core_entity.py

Lines changed: 9 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from typing import ClassVar
55

66
import abc
7-
import os
87

98
from . import types as t
109
from ._errors import TaxBenefitSystemUnsetError, VariableNotFoundError
@@ -103,6 +102,9 @@ def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
103102
>>> that.variables
104103
{'tax': <openfisca_core.entities._core_entity.tax object at ...>}
105104
105+
>>> that.variables["tax"]
106+
<openfisca_core.entities._core_entity.tax object at ...>
107+
106108
"""
107109
if self.tax_benefit_system is None:
108110
raise TaxBenefitSystemUnsetError
@@ -115,6 +117,7 @@ def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
115117
def get_variable(
116118
self,
117119
variable_name: t.VariableName,
120+
/,
118121
check_existence: bool = False,
119122
) -> None | t.Variable:
120123
"""Get ``variable_name`` from ``variables``.
@@ -173,81 +176,11 @@ def get_variable(
173176
"""
174177
if self.tax_benefit_system is None:
175178
raise TaxBenefitSystemUnsetError
176-
if not check_existence:
177-
return self.variables.get(variable_name)
178-
try:
179-
return self.variables[variable_name]
180-
except KeyError as error:
181-
raise VariableNotFoundError(variable_name, self.plural) from error
182-
183-
def check_variable_defined_for_entity(self, variable_name: t.VariableName) -> None:
184-
"""Check if ``variable_name`` is defined for ``self``.
185-
186-
Args:
187-
variable_name: The ``Variable`` to be found.
188-
189-
Raises:
190-
ValueError: When the ``Variable`` exists but is defined
191-
for another ``Entity``.
192-
193-
Examples:
194-
>>> from openfisca_core import (
195-
... entities,
196-
... periods,
197-
... taxbenefitsystems,
198-
... variables,
199-
... )
200-
201-
>>> this = entities.SingleEntity("this", "", "", "")
202-
>>> that = entities.SingleEntity("that", "", "", "")
203-
>>> tax_benefit_system = taxbenefitsystems.TaxBenefitSystem([that])
204-
>>> this.tax_benefit_system = tax_benefit_system
205-
206-
>>> this.check_variable_defined_for_entity("tax")
207-
Traceback (most recent call last):
208-
VariableNotFoundError: You tried to calculate or to set a value...
209-
210-
>>> class tax(variables.Variable):
211-
... definition_period = periods.WEEK
212-
... value_type = int
213-
... entity = that
214-
215-
>>> this.tax_benefit_system.add_variable(tax)
216-
<openfisca_core.entities._core_entity.tax object at ...>
217-
218-
>>> this.check_variable_defined_for_entity("tax")
219-
Traceback (most recent call last):
220-
ValueError: You tried to compute the variable 'tax' for the enti...
221-
222-
>>> tax.entity = this
223-
224-
>>> this.tax_benefit_system.update_variable(tax)
225-
<openfisca_core.entities._core_entity.tax object at ...>
226-
227-
>>> this.check_variable_defined_for_entity("tax")
228-
229-
"""
230-
entity: None | t.CoreEntity = None
231-
variable: None | t.Variable = self.get_variable(
232-
variable_name,
233-
check_existence=True,
234-
)
235-
236-
if variable is not None:
237-
entity = variable.entity
238-
239-
if entity is None:
240-
return
241-
242-
if entity.key != self.key:
243-
message = (
244-
f"You tried to compute the variable '{variable_name}' for",
245-
f"the entity '{self.plural}'; however the variable",
246-
f"'{variable_name}' is defined for '{entity.plural}'.",
247-
"Learn more about entities in our documentation:",
248-
"<https://openfisca.org/doc/coding-the-legislation/50_entities.html>.",
249-
)
250-
raise ValueError(os.linesep.join(message))
179+
if (variable := self.variables.get(variable_name)) is not None:
180+
return variable
181+
if check_existence:
182+
raise VariableNotFoundError(variable_name, self.plural)
183+
return None
251184

252185

253186
__all__ = ["CoreEntity"]

openfisca_core/entities/_errors.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def __init__(self) -> None:
1212
super().__init__(msg)
1313

1414

15-
class VariableNotFoundError(IndexError):
15+
class VariableNotFoundError(ValueError):
1616
"""Raised when a requested variable is not defined for as entity."""
1717

1818
def __init__(self, name: t.VariableName, plural: t.EntityPlural) -> None:
@@ -23,8 +23,8 @@ def __init__(self, name: t.VariableName, plural: t.EntityPlural) -> None:
2323
"this is most probably linked to an update of the tax and "
2424
"benefit system. Look at its CHANGELOG to learn about renames "
2525
"and removals and update your code accordingly."
26-
"Learn more about entities in our documentation:",
27-
"<https://openfisca.org/doc/coding-the-legislation/50_entities.html>.",
26+
"Learn more about entities in our documentation:"
27+
"<https://openfisca.org/doc/coding-the-legislation/50_entities.html>."
2828
)
2929
super().__init__(msg)
3030

openfisca_core/populations/_core_population.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def __call__(
142142
option=options,
143143
)
144144

145-
self.entity.check_variable_defined_for_entity(calculate.variable)
145+
self.entity.get_variable(calculate.variable, check_existence=True)
146146
self.check_period_validity(calculate.variable, calculate.period)
147147

148148
if not isinstance(calculate.option, Sequence):
@@ -380,7 +380,7 @@ def get_holder(self, variable_name: t.VariableName) -> t.Holder:
380380
<openfisca_core.holders.holder.Holder object at ...
381381
382382
"""
383-
self.entity.check_variable_defined_for_entity(variable_name)
383+
self.entity.get_variable(variable_name, check_existence=True)
384384
holder = self._holders.get(variable_name)
385385
if holder:
386386
return holder

openfisca_core/simulations/simulation_builder.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ def init_variable_values(self, entity, instance_object, instance_id) -> None:
592592
for variable_name, variable_values in instance_object.items():
593593
path_in_json = [entity.plural, instance_id, variable_name]
594594
try:
595-
entity.check_variable_defined_for_entity(variable_name)
595+
entity.get_variable(variable_name, check_existence=True)
596596
except ValueError as e: # The variable is defined for another entity
597597
raise errors.SituationParsingError(path_in_json, e.args[0])
598598
except errors.VariableNotFoundError as e: # The variable doesn't exist
@@ -665,6 +665,8 @@ def finalize_variables_init(self, population) -> None:
665665
for variable_name in self.input_buffer:
666666
try:
667667
holder = population.get_holder(variable_name)
668+
# TODO(Mauko Quiroga-Alvarado): We should handle this differently.
669+
# It cost me a lot of time to figure out that this was the problem.
668670
except ValueError: # Wrong entity, we can just ignore that
669671
continue
670672
buffer = self.input_buffer[variable_name]

openfisca_core/types.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from __future__ import annotations
22

3-
from collections.abc import Iterable, Sequence, Sized
3+
from collections.abc import Iterable, Mapping, Sequence, Sized
44
from numpy.typing import DTypeLike, NDArray
55
from typing import NewType, TypeVar, Union
66
from typing_extensions import Protocol, Required, Self, TypeAlias, TypedDict
@@ -71,19 +71,23 @@
7171

7272

7373
class CoreEntity(Protocol):
74-
key: EntityKey
75-
plural: EntityPlural
76-
77-
def check_variable_defined_for_entity(
78-
self,
79-
variable_name: VariableName,
80-
/,
81-
) -> None: ...
74+
@property
75+
def key(self, /) -> EntityKey: ...
76+
@property
77+
def plural(self, /) -> EntityPlural: ...
78+
@property
79+
def label(self, /) -> str: ...
80+
@property
81+
def doc(self, /) -> str: ...
82+
@property
83+
def tax_benefit_system(self, /) -> None | TaxBenefitSystem: ...
84+
@property
85+
def variables(self, /) -> Mapping[VariableName, Variable]: ...
8286
def get_variable(
8387
self,
84-
variable_name: VariableName,
85-
check_existence: bool = ...,
88+
name: VariableName,
8689
/,
90+
check_existence: bool = ...,
8791
) -> None | Variable: ...
8892

8993

tests/fixtures/entities.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import pytest
24

35
from openfisca_core.entities import Entity, GroupEntity
@@ -10,28 +12,22 @@ def get_variable(
1012
self,
1113
variable_name: str,
1214
check_existence: bool = False,
13-
) -> TestVariable:
15+
) -> None | TestVariable:
1416
result = TestVariable(self)
1517
result.name = variable_name
1618
return result
1719

18-
def check_variable_defined_for_entity(self, variable_name: str) -> bool:
19-
return True
20-
2120

2221
class TestGroupEntity(GroupEntity):
2322
def get_variable(
2423
self,
2524
variable_name: str,
2625
check_existence: bool = False,
27-
) -> TestVariable:
26+
) -> None | TestVariable:
2827
result = TestVariable(self)
2928
result.name = variable_name
3029
return result
3130

32-
def check_variable_defined_for_entity(self, variable_name: str) -> bool:
33-
return True
34-
3531

3632
@pytest.fixture
3733
def persons():

tests/web_api/test_calculate.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,15 @@ def check_response(
5252
),
5353
(
5454
'{"persons": {"bob": {"unknown_variable": {}}}}',
55-
client.NOT_FOUND,
55+
client.BAD_REQUEST,
5656
"persons/bob/unknown_variable",
57-
"You tried to calculate or to set",
57+
"You requested the variable 'unknown_variable', but it was not found in the entity 'persons'",
5858
),
5959
(
6060
'{"persons": {"bob": {"housing_allowance": {}}}}',
6161
client.BAD_REQUEST,
6262
"persons/bob/housing_allowance",
63-
"You tried to compute the variable 'housing_allowance' for the entity 'persons'",
63+
"You requested the variable 'housing_allowance', but it was not found in the entity 'persons'",
6464
),
6565
(
6666
'{"persons": {"bob": {"salary": 4000 }}}',

0 commit comments

Comments
 (0)