Set the attribute. If the attribute is inherited, set the attribute on the parent state. Args: name: The name of the attribute. value: The value of the attribute. Raises: SetUndefinedStateVarError: If a value of a var is set without firs
(self, name: str, value: Any)
| 1486 | __getattribute__ = _get_attribute |
| 1487 | |
| 1488 | def __setattr__(self, name: str, value: Any): |
| 1489 | """Set the attribute. |
| 1490 | |
| 1491 | If the attribute is inherited, set the attribute on the parent state. |
| 1492 | |
| 1493 | Args: |
| 1494 | name: The name of the attribute. |
| 1495 | value: The value of the attribute. |
| 1496 | |
| 1497 | Raises: |
| 1498 | SetUndefinedStateVarError: If a value of a var is set without first defining it. |
| 1499 | """ |
| 1500 | if name.startswith("__") or name in CLASS_VAR_NAMES: |
| 1501 | # Fast path for dunder and class vars |
| 1502 | object.__setattr__(self, name, value) |
| 1503 | return |
| 1504 | |
| 1505 | if isinstance(value, MutableProxy): |
| 1506 | # unwrap proxy objects when assigning back to the state |
| 1507 | value = value.__wrapped__ |
| 1508 | |
| 1509 | # Set the var on the parent state. |
| 1510 | if name in self.inherited_vars or name in self.inherited_backend_vars: |
| 1511 | setattr(self.parent_state, name, value) |
| 1512 | return |
| 1513 | |
| 1514 | if name in self.backend_vars: |
| 1515 | self._backend_vars.__setitem__(name, value) |
| 1516 | self.dirty_vars.add(name) |
| 1517 | self._mark_dirty() |
| 1518 | return |
| 1519 | |
| 1520 | if ( |
| 1521 | name not in self.vars |
| 1522 | and name not in self.get_skip_vars() |
| 1523 | and not name.startswith("__") |
| 1524 | and not name.startswith( |
| 1525 | f"_{getattr(type(self), '__original_name__', type(self).__name__)}__" |
| 1526 | ) |
| 1527 | ): |
| 1528 | msg = ( |
| 1529 | f"The state variable '{name}' has not been defined in '{type(self).__name__}'. " |
| 1530 | f"All state variables must be declared before they can be set." |
| 1531 | ) |
| 1532 | raise SetUndefinedStateVarError(msg) |
| 1533 | |
| 1534 | fields = self.get_fields() |
| 1535 | |
| 1536 | if (field := fields.get(name)) is not None and field.is_var: |
| 1537 | field_type = field.outer_type_ |
| 1538 | if not _isinstance(value, field_type, nested=1, treat_var_as_type=False): |
| 1539 | console.error( |
| 1540 | f"Expected field '{type(self).__name__}.{name}' to receive type '{escape(str(field_type))}'," |
| 1541 | f" but got '{value}' of type '{type(value)}'." |
| 1542 | ) |
| 1543 | |
| 1544 | # Set the attribute. |
| 1545 | object.__setattr__(self, name, value) |