reflex-dev / reflex

🕸️ Web apps in pure Python 🐍
https://reflex.dev
Apache License 2.0
19.06k stars 1.08k forks source link

rx.var/property setters #3772

Open benedikt-bartscher opened 1 month ago

benedikt-bartscher commented 1 month ago
class State(rx.State):
    _test: str = "hi"

    @rx.var
    def test(self) -> str:
        return self._test

    @test.setter
    def test(self, value: str):
        self._test = value

    def other_handler(self):
        self.test = "hello"

With this example, State.test would be a BaseVar or EventHandler depending on where it is used

picklelo commented 1 month ago

I don't understand the @test.setter annotation here. Generally I'm hesitant to do something like this where the reference changes based on the context.

benedikt-bartscher commented 1 month ago

@picklelo it's a design pattern from python properties, take a look here: https://docs.python.org/3/library/functions.html#property

Btw, the code above currently fails with this error:

TypeError: No JSON serializer found for State Var 'test' of value <function State.test at 0x7bfe9d21dbc0> of type <class 'function'>.

It does not fail while interpreting @test.setter. It is actually defined because ComputedVar inherits it from property. We could at least ignore those setters or raise a better exception message.