Skip to content

@rx._x.hybrid_property should work on a model/dataclass #6617

@masenf

Description

@masenf

Describe the Enhancement you want

we want to support the following code

from dataclasses import dataclass

import reflex as rx
from reflex.experimental.hybrid_property import hybrid_property


@dataclass
class Info:
    a: str
    b: str

    @hybrid_property
    def a_b(self) -> str:
        return f"{self.a} - {self.b}"


class State(rx.State):
    info: Info = Info(a="a", b="b")


def index() -> rx.Component:
    return rx.vstack(
        rx.text(
            State.info.a,
        ),
        rx.text(
            State.info.b,
        ),
        rx.text(
            State.info.a_b,
        ),
        spacing="5",
    )


app = rx.App()
app.add_page(index)

discussion on discord

Bert — 10:27
If you do decide to support dataclasses, then please consider also supporting the SQLAchemy "dataclass" equivalent i.e..:

class Base(MappedAsDataclass, DeclarativeBase, kw_only=True)
masenf — 10:31
i'm assuming it works as expected in the backend? you're just needing it to render as a var when used in the frontend
Bert — 10:40
Correct but since the dataclass @Property doesn't work on the client side in any version it has limited use on the server side. To get around this I typically use BaseModel (Pydantic) with:
@computed_field
@Property

But that will create, cache and send the combined fields. A typical example is I have several fields that together are used to create a unique id (e.g. manufacturer + product id)

With the new @Hybrid property, we could save the extra baggage especially if we have multiple different representations based on the other attributes in the class.

So that brings up that it would also be nice to support it in pydantic BaseModel classes since @Hybrid property would be better there too...

masenf — 10:42
if we support it anywhere, it should be supported everywhere, because under the hood we treat BaseModel, dataclass, declarative base, etc all as ObjectVar

Additional context
When the property State.info.a_b is accessed in the frontend, it should use Var-access semantics as if the hybrid_property was directly accessed on the state

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementAnything you want improved

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions