Skip to content

Commit a3cd58d

Browse files
committed
feat: add CoreEntity.variables
1 parent 6af247e commit a3cd58d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

openfisca_core/entities/_core_entity.py

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

3+
from collections.abc import Mapping
34
from typing import ClassVar
45

56
import abc
@@ -52,6 +53,64 @@ def __init__(self, *__args: object, **__kwargs: object) -> None: ...
5253
def __repr__(self) -> str:
5354
return f"{self.__class__.__name__}({self.key})"
5455

56+
@property
57+
def variables(self, /) -> Mapping[t.VariableName, t.Variable]:
58+
"""Get all variables defined for the entity.
59+
60+
Returns:
61+
dict[str, Variable]: The variables defined for the entity.
62+
63+
Raises:
64+
ValueError: When the :attr:`.tax_benefit_system` is not set yet.
65+
66+
Examples:
67+
>>> from openfisca_core import (
68+
... entities,
69+
... periods,
70+
... taxbenefitsystems,
71+
... variables,
72+
... )
73+
74+
>>> this = entities.SingleEntity("this", "", "", "")
75+
>>> that = entities.SingleEntity("that", "", "", "")
76+
77+
>>> this.variables
78+
Traceback (most recent call last):
79+
ValueError: You must set 'tax_benefit_system' to call this method.
80+
81+
>>> tbs = taxbenefitsystems.TaxBenefitSystem([this, that])
82+
>>> this, that = tbs.entities
83+
84+
>>> this.variables
85+
{}
86+
87+
>>> that.variables
88+
{}
89+
90+
>>> class tax(variables.Variable):
91+
... definition_period = periods.MONTH
92+
... value_type = float
93+
... entity = that
94+
95+
>>> tbs.add_variable(tax)
96+
<openfisca_core.entities._core_entity.tax object at ...>
97+
98+
>>> this.variables
99+
{}
100+
101+
>>> that.variables
102+
{'tax': <openfisca_core.entities._core_entity.tax object at ...>}
103+
104+
"""
105+
if self.tax_benefit_system is None:
106+
msg = "You must set 'tax_benefit_system' to call this method."
107+
raise ValueError(msg)
108+
return {
109+
name: variable
110+
for name, variable in self.tax_benefit_system.variables.items()
111+
if variable.entity.key == self.key
112+
}
113+
55114
def get_variable(
56115
self,
57116
variable_name: t.VariableName,

0 commit comments

Comments
 (0)