Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cast dict as model type if annotated #4264

Open
masenf opened this issue Oct 29, 2024 · 2 comments
Open

Cast dict as model type if annotated #4264

masenf opened this issue Oct 29, 2024 · 2 comments
Assignees
Labels
bug Something isn't working

Comments

@masenf
Copy link
Collaborator

masenf commented Oct 29, 2024

Describe the bug
Event handlers always seem to get a dict even when the user expects to get a particular type.

To Reproduce

import reflex as rx


class Amigo(rx.Base):
    nombre: str
    anos: int

class State(rx.State):
    amigos: list[Amigo] = [
        Amigo(nombre="Juan", anos=20),
        Amigo(nombre="Pedro", anos=30),
        Amigo(nombre="Maria", anos=40),
        Amigo(nombre="Jose", anos=50),
    ]

    amigo_actual: Amigo | None

    def set_amigo_actual(self, amigo: Amigo) -> None:
        print(repr(amigo))
        self.amigo_actual = amigo


def hacer_amigo(a: Amigo) -> rx.Component:
    return rx.button(a.nombre, on_click=State.set_amigo_actual(a))


def index() -> rx.Component:
    return rx.container(
        rx.color_mode.button(position="top-right"),
        rx.vstack(
            rx.heading("Welcome to Reflex!", size="9"),
            rx.text(f"Amigo Actual: {State.amigo_actual.nombre}"),
            rx.foreach(
                State.amigos,
                hacer_amigo,
            )
        ),
        rx.logo(),
    )


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

Expected behavior
The argument received by the set_amigo_actual event handler should be an Amigo, not a dict.

Specifics (please complete the following information):

  • Python Version: 3.12
  • Reflex Version: 0.6.4a3
  • OS: macOS / Any

Additional context
From this forum thread https://forum.reflex.dev/t/understanding-state-types/488

However this is a long-standing problem in Reflex in that arguments passed to event handlers are always the bare un-JSON'd type, rather than the preferred model type.

There is some provision for casting number-type arguments to actual int/float before passing them through to the event handler, but this logic does not apply for dict types that are annotated with another, specific type.

@masenf masenf added the bug Something isn't working label Oct 29, 2024
Copy link

linear bot commented Oct 29, 2024

@benedikt-bartscher
Copy link
Contributor

I think we need a flexible way to register deserialization/unmarshalling functions like reflex already does for serialization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants