Replies: 1 comment
|
Call the dataclass method inside a backend computed var, then render that computed value. In a component function, For your example: from dataclasses import dataclass
import reflex as rx
@dataclass
class Test:
v1: int
def compute(self, v2: int) -> int:
return self.v1 - v2
class State(rx.State):
test: Test = Test(v1=10)
v2: int = 2
@rx.var
def computed_value(self) -> int:
return self.test.compute(self.v2)
@rx.event
def increase_v2(self):
self.v2 += 1
def index():
return rx.vstack(
rx.text(State.computed_value),
rx.button("Increase argument", on_click=State.increase_v2),
)The argument lives in state, so If a view needs results for several arguments at once, have a computed var return a typed list/dictionary of those results and render/index that data. For a calculation that should happen only on a click, call the method in an event handler and store its result instead. The static-method workaround only helps if its body uses operations Reflex can compile into frontend expressions. It doesn't make arbitrary Python code execute in the browser. References: computed vars run on the backend and custom vars must be serializable. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I see that Computed Vars cannot take arguments, but I also see that I cannot use any methods on the var to make computations.
Say I have:
I'm aware this is a toy example and I can do
var - somethingalready because of the built in functions. The actual function I'm dealing with does a bit more which is why I want to encapsulate it in one place and reuse throughout the view layer instead of writing it out multiple times.However the var system is not able to find this compute method, as in when I write
rx.text(f"{test.compute(2)")I getreflex.utils.exceptions.VarAttributeError: The State varteamof type <class 'schema.Test'> has no attribute 'compute' or may have been annotated wrongly.And when I try to annotate with
@rx.varI getComputed var compute(self, year: int) -> intcannot take arguments.How exactly do I access this method on the var and use it from within the view layer?
I suppose one workaround is to define these as @staticmethod and then call it as Test.compute(test, 2) but this feels kind of clunky and not how I would expect to use a class normally in python.
All reactions