Skip to content

Commit 8f04683

Browse files
committed
refactor: make CoreEntity.get_variable reuse .variables
1 parent a3cd58d commit 8f04683

File tree

3 files changed

+63
-21
lines changed

3 files changed

+63
-21
lines changed

openfisca_core/entities/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from . import types
44
from ._core_entity import CoreEntity
5+
from ._errors import TaxBenefitSystemUnsetError, VariableNotFoundError
56
from .entity import Entity
67
from .group_entity import GroupEntity
78
from .helpers import build_entity, find_role
@@ -15,6 +16,8 @@
1516
"GroupEntity",
1617
"Role",
1718
"SingleEntity",
19+
"TaxBenefitSystemUnsetError",
20+
"VariableNotFoundError",
1821
"build_entity",
1922
"find_role",
2023
"types",

openfisca_core/entities/_core_entity.py

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os
88

99
from . import types as t
10+
from ._errors import TaxBenefitSystemUnsetError, VariableNotFoundError
1011

1112

1213
class CoreEntity:
@@ -61,7 +62,8 @@ def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
6162
dict[str, Variable]: The variables defined for the entity.
6263
6364
Raises:
64-
ValueError: When the :attr:`.tax_benefit_system` is not set yet.
65+
TaxBenefitSystemUnsetError: When the :attr:`.tax_benefit_system` is
66+
not set yet.
6567
6668
Examples:
6769
>>> from openfisca_core import (
@@ -71,12 +73,12 @@ def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
7173
... variables,
7274
... )
7375
74-
>>> this = entities.SingleEntity("this", "", "", "")
75-
>>> that = entities.SingleEntity("that", "", "", "")
76+
>>> this = entities.SingleEntity("this", "these", "", "")
77+
>>> that = entities.SingleEntity("that", "those", "", "")
7678
7779
>>> this.variables
7880
Traceback (most recent call last):
79-
ValueError: You must set 'tax_benefit_system' to call this method.
81+
TaxBenefitSystemUnsetError: The tax and benefit system is not se...
8082
8183
>>> tbs = taxbenefitsystems.TaxBenefitSystem([this, that])
8284
>>> this, that = tbs.entities
@@ -103,8 +105,7 @@ def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
103105
104106
"""
105107
if self.tax_benefit_system is None:
106-
msg = "You must set 'tax_benefit_system' to call this method."
107-
raise ValueError(msg)
108+
raise TaxBenefitSystemUnsetError
108109
return {
109110
name: variable
110111
for name, variable in self.tax_benefit_system.variables.items()
@@ -115,7 +116,7 @@ def get_variable(
115116
self,
116117
variable_name: t.VariableName,
117118
check_existence: bool = False,
118-
) -> t.Variable | None:
119+
) -> None | t.Variable:
119120
"""Get ``variable_name`` from ``variables``.
120121
121122
Args:
@@ -127,9 +128,10 @@ def get_variable(
127128
None: When the ``Variable`` doesn't exist.
128129
129130
Raises:
130-
ValueError: When the :attr:`_tax_benefit_system` is not set yet.
131-
ValueError: When ``check_existence`` is ``True`` and
132-
the ``Variable`` doesn't exist.
131+
TaxBenefitSystemUnsetError: When the :attr:`.tax_benefit_system` is
132+
not set yet.
133+
VariableNotFoundError: When ``check_existence`` is ``True`` and the
134+
``Variable`` doesn't exist.
133135
134136
Examples:
135137
>>> from openfisca_core import (
@@ -139,39 +141,44 @@ def get_variable(
139141
... variables,
140142
... )
141143
142-
>>> this = entities.SingleEntity("this", "", "", "")
143-
>>> that = entities.SingleEntity("that", "", "", "")
144+
>>> this = entities.SingleEntity("this", "these", "", "")
145+
>>> that = entities.SingleEntity("that", "those", "", "")
144146
145147
>>> this.get_variable("tax")
146148
Traceback (most recent call last):
147-
ValueError: You must set 'tax_benefit_system' before calling this...
149+
TaxBenefitSystemUnsetError: The tax and benefit system is not se...
148150
149-
>>> tax_benefit_system = taxbenefitsystems.TaxBenefitSystem([this])
150-
>>> this.tax_benefit_system = tax_benefit_system
151+
>>> tbs = taxbenefitsystems.TaxBenefitSystem([this, that])
152+
>>> this, that = tbs.entities
151153
152154
>>> this.get_variable("tax")
153155
154156
>>> this.get_variable("tax", check_existence=True)
155157
Traceback (most recent call last):
156-
VariableNotFoundError: You tried to calculate or to set a value...
158+
VariableNotFoundError: You requested the variable 'tax', but it ...
157159
158160
>>> class tax(variables.Variable):
159161
... definition_period = periods.MONTH
160162
... value_type = float
161163
... entity = that
162164
163-
>>> this.tax_benefit_system.add_variable(tax)
165+
>>> tbs.add_variable(tax)
164166
<openfisca_core.entities._core_entity.tax object at ...>
165167
166168
>>> this.get_variable("tax")
167-
<openfisca_core.entities._core_entity.tax object at ...>
168169
170+
>>> that.get_variable("tax")
171+
<openfisca_core.entities._core_entity.tax object at ...>
169172
170173
"""
171174
if self.tax_benefit_system is None:
172-
msg = "You must set 'tax_benefit_system' to call this method."
173-
raise ValueError(msg)
174-
return self.tax_benefit_system.get_variable(variable_name, check_existence)
175+
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
175182

176183
def check_variable_defined_for_entity(self, variable_name: t.VariableName) -> None:
177184
"""Check if ``variable_name`` is defined for ``self``.

openfisca_core/entities/_errors.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from . import types as t
2+
3+
4+
class TaxBenefitSystemUnsetError(ValueError):
5+
"""Raised when a tax and benefit system is not set yet."""
6+
7+
def __init__(self) -> None:
8+
msg = (
9+
"The tax and benefit system is not set yet. You need to set it "
10+
"before using this method: `entity.tax_benefit_system = ...`."
11+
)
12+
super().__init__(msg)
13+
14+
15+
class VariableNotFoundError(IndexError):
16+
"""Raised when a requested variable is not defined for as entity."""
17+
18+
def __init__(self, name: t.VariableName, plural: t.EntityPlural) -> None:
19+
msg = (
20+
f"You requested the variable '{name}', but it was not found in "
21+
f"the entity '{plural}'. Are you sure you spelled '{name}' "
22+
"correctly? If this code used to work and suddenly does not, "
23+
"this is most probably linked to an update of the tax and "
24+
"benefit system. Look at its CHANGELOG to learn about renames "
25+
"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>.",
28+
)
29+
super().__init__(msg)
30+
31+
32+
__all__ = ["TaxBenefitSystemUnsetError", "VariableNotFoundError"]

0 commit comments

Comments
 (0)