Get the value of an rx.Var from another state. Args: var: The var to get the value for. Returns: The value of the var. Raises: UnretrievableVarValueError: If the var does not have a literal value or associated state.
(self, var: Var[VAR_TYPE])
| 1742 | return await self._get_state_from_redis(state_cls) |
| 1743 | |
| 1744 | async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE: |
| 1745 | """Get the value of an rx.Var from another state. |
| 1746 | |
| 1747 | Args: |
| 1748 | var: The var to get the value for. |
| 1749 | |
| 1750 | Returns: |
| 1751 | The value of the var. |
| 1752 | |
| 1753 | Raises: |
| 1754 | UnretrievableVarValueError: If the var does not have a literal value |
| 1755 | or associated state. |
| 1756 | """ |
| 1757 | # Oopsie case: you didn't give me a Var... so get what you give. |
| 1758 | if not isinstance(var, Var): |
| 1759 | return var |
| 1760 | |
| 1761 | unset = object() |
| 1762 | |
| 1763 | # Fast case: this is a literal var and the value is known. |
| 1764 | if ( |
| 1765 | var_value := getattr(var, "_var_value", unset) |
| 1766 | ) is not unset and not isinstance(var_value, Var): |
| 1767 | return var_value # pyright: ignore [reportReturnType] |
| 1768 | |
| 1769 | # Unwrap any cast wrappers and resolve via the underlying var's *own* |
| 1770 | # var data, not the recursive _get_all_var_data(). For an operation or |
| 1771 | # derived var (e.g. State.a + State.b or State.items[0]), the recursive |
| 1772 | # merge back-fills state/field_name from the first operand, which would |
| 1773 | # make us silently return that operand's value instead of the operation's |
| 1774 | # result. Only a plain field or computed var reference carries |
| 1775 | # state + field_name on its own var data. |
| 1776 | inner_var = var |
| 1777 | while isinstance(inner_var, ToOperation): |
| 1778 | inner_var = inner_var._original |
| 1779 | var_data = inner_var._var_data |
| 1780 | if var_data is None or not var_data.state or not var_data.field_name: |
| 1781 | msg = f"Unable to retrieve value for {var._js_expr}: not associated with any state." |
| 1782 | raise UnretrievableVarValueError(msg) |
| 1783 | # Fastish case: this var belongs to this state |
| 1784 | if var_data.state == self.get_full_name(): |
| 1785 | value = getattr(self, var_data.field_name) |
| 1786 | if inspect.isawaitable(value): |
| 1787 | return await value |
| 1788 | return value |
| 1789 | |
| 1790 | # Slow case: this var belongs to another state |
| 1791 | other_state = await self.get_state( |
| 1792 | self._get_root_state().get_class_substate(var_data.state) |
| 1793 | ) |
| 1794 | value = getattr(other_state, var_data.field_name) |
| 1795 | if inspect.isawaitable(value): |
| 1796 | return await value |
| 1797 | return value |
| 1798 | |
| 1799 | def _mark_dirty_computed_vars(self) -> None: |
| 1800 | """Mark ComputedVars that need to be recalculated based on dirty_vars.""" |