Skip to content

Accessing a computed Var in a Base object #3205

Answered by picklelo
hpharmsen asked this question in Q&A
Discussion options

You must be logged in to vote

@hpharmsen The @rx.var decorator only works within state classes (not within the a Base class as you have it here). You want to use the @property decorator that's builtin to Python instead.

It looks like Pydantic supports computed_fields from their v2.0 but We are still using 1.10 in Reflex.

Here's a way to do this currently by overriding the dict method to make sure the property gets serialized:

import reflex as rx

class Person(rx.Base):
    name: str

    @property
    def hello_name(self) -> str:
        return "Hello " + self.name

    def dict(self, **kwargs):
        return super().dict(**kwargs) | {"hello_name": self.hello_name}


class State(rx.State):
    count: int = 5
    persons

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@hpharmsen
Comment options

@picklelo
Comment options

@hpharmsen
Comment options

Answer selected by hpharmsen
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants