reflex-dev / reflex

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

Minor: Deprecation warning is shown for correctly typed fields. #4296

Closed abulvenz closed 3 weeks ago

abulvenz commented 3 weeks ago

Describe the bug

Clicking "Click me!" or "Click me optionally!" results in a deprecation warning. DeprecationWarning: mismatched-type-assignment has been deprecated in version 0.6.5 Tried to assign value Hello, Reflex! of type <class 'str'> to field State.string_var of type reflex.vars.base.Field. This might lead to unexpected behavior. It will be completely removed in 0.7.0

I guess the type resolution should be done as in state.py::get_var_for_field(), where there is a branch depending on if it is an rx.Field. Since I don't know what plans are for the check when 0.7.0 comes, I cannot come up with a fix right now.

import reflex as rx

class State(rx.State):
    string_var: rx.Field[str] = rx.field("Hello, World!")
    optional_string_var: rx.Field[str | None] = rx.field(None)
    non_field_str_var: str = "Hello, non-field!"

    @rx.event
    def set_string_var(self, new_string: str) -> None:
        self.string_var = new_string
        for k, v in self.get_fields().items():
            print(k, v.type_)

    @rx.event
    def set_optional_string_var(self, new_string: str) -> None:
        self.optional_string_var = new_string

    @rx.event
    def set_non_field_str_var(self, new_string: str) -> None:
        self.non_field_str_var = new_string

def index() -> rx.Component:
    return rx.container(
        rx.button("Click me!", on_click=State.set_string_var("Hello, Reflex!")),
        rx.button("Click me optionally!", on_click=State.set_optional_string_var("Hello maybe, Reflex!")),
        rx.button("Click me non-field!", on_click=State.set_non_field_str_var("Hello, non-field!")),
    )

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

Printing the resulting ModelField.type_ for all in get_fields() as in the code above yields:

parent_state <class 'reflex.state.BaseState'>
substates <class 'reflex.state.BaseState'>
dirty_vars <class 'str'>
dirty_substates <class 'str'>
router_data typing.Any
router <class 'reflex.istate.data.RouterData'>
is_hydrated <class 'bool'>
string_var <class 'reflex.vars.base.Field'>
optional_string_var <class 'reflex.vars.base.Field'>
non_field_str_var <class 'str'>

Maybe a get_field_type() method should be added or an reflex-own subclass of ModelField should be used where type_ already performs the resolution.

linear[bot] commented 3 weeks ago

ENG-4042 Minor: Deprecation warning is shown for correctly typed fields.