Add dynamically a variable to the State. The variable added this way can be used in the same way as a variable defined statically in the model. Args: name: The name of the variable type_: The type of the variable default_value: The defaul
(cls, name: str, type_: Any, default_value: Any = None)
| 1175 | |
| 1176 | @classmethod |
| 1177 | def add_var(cls, name: str, type_: Any, default_value: Any = None): |
| 1178 | """Add dynamically a variable to the State. |
| 1179 | |
| 1180 | The variable added this way can be used in the same way as a variable |
| 1181 | defined statically in the model. |
| 1182 | |
| 1183 | Args: |
| 1184 | name: The name of the variable |
| 1185 | type_: The type of the variable |
| 1186 | default_value: The default value of the variable |
| 1187 | |
| 1188 | Raises: |
| 1189 | NameError: if a variable of this name already exists |
| 1190 | """ |
| 1191 | if name in cls.__fields__: |
| 1192 | msg = f"The variable '{name}' already exist. Use a different name" |
| 1193 | raise NameError(msg) |
| 1194 | |
| 1195 | # create the variable based on name and type |
| 1196 | var = Var( |
| 1197 | _js_expr=format.format_state_name(cls.get_full_name()) |
| 1198 | + "." |
| 1199 | + name |
| 1200 | + FIELD_MARKER, |
| 1201 | _var_type=type_, |
| 1202 | _var_data=VarData.from_state(cls, name), |
| 1203 | ).guess_type() |
| 1204 | |
| 1205 | # add the field dynamically (must be done before _init_var) |
| 1206 | cls.add_field(name, var, default_value) |
| 1207 | |
| 1208 | cls._init_var(name, var) |
| 1209 | |
| 1210 | # update the internal dicts so the new variable is correctly handled |
| 1211 | cls.base_vars.update({name: var}) |
| 1212 | cls.vars.update({name: var}) |
| 1213 | |
| 1214 | # let substates know about the new variable |
| 1215 | for substate_class in cls.get_substates(): |
| 1216 | substate_class.vars.setdefault(name, var) |
| 1217 | |
| 1218 | # Reinitialize dependency tracking dicts. |
| 1219 | cls._init_var_dependency_dicts() |
| 1220 | |
| 1221 | @classmethod |
| 1222 | def _set_var(cls, name: str, prop: Var): |