Browse Source

add more type annotations through the code (#4401)

* add more type annotations through the code

* add typing in reflex/utils

* misc typing

* more typings

* state typing

* keep typing

* typing init and utils

* more typing for components

* fix attempt for 3.9

* need more __future

* more typings

* type event plz

* type model

* type vars/base.py

* enable 'ANN001' for reflex folder (ignore tests and benchmarks)

* fix pyi

* add missing annotations

* use more precise error when ignoring
Thomas Brandého 3 months ago
parent
commit
b8b3f8910e
54 changed files with 286 additions and 214 deletions
  1. 3 3
      pyproject.toml
  2. 4 1
      reflex/__init__.py
  3. 18 19
      reflex/app.py
  4. 1 1
      reflex/app_mixins/lifespan.py
  5. 1 1
      reflex/base.py
  6. 1 1
      reflex/compiler/utils.py
  7. 5 5
      reflex/components/component.py
  8. 1 1
      reflex/components/core/client_side_routing.py
  9. 1 1
      reflex/components/core/client_side_routing.pyi
  10. 1 1
      reflex/components/core/cond.py
  11. 1 1
      reflex/components/core/match.py
  12. 2 4
      reflex/components/datadisplay/logo.py
  13. 1 1
      reflex/components/el/element.py
  14. 5 3
      reflex/components/markdown/markdown.py
  15. 3 1
      reflex/components/next/image.py
  16. 1 1
      reflex/components/props.py
  17. 7 5
      reflex/components/radix/themes/color_mode.py
  18. 1 1
      reflex/components/radix/themes/layout/list.py
  19. 1 1
      reflex/components/recharts/charts.py
  20. 10 10
      reflex/components/sonner/toast.py
  21. 5 5
      reflex/components/sonner/toast.pyi
  22. 6 4
      reflex/components/suneditor/editor.py
  23. 2 2
      reflex/components/suneditor/editor.pyi
  24. 1 1
      reflex/components/tags/tag.py
  25. 3 3
      reflex/config.py
  26. 1 1
      reflex/custom_components/custom_components.py
  27. 7 6
      reflex/event.py
  28. 5 5
      reflex/experimental/hooks.py
  29. 3 3
      reflex/experimental/misc.py
  30. 1 1
      reflex/istate/wrappers.py
  31. 9 4
      reflex/model.py
  32. 3 3
      reflex/page.py
  33. 12 8
      reflex/reflex.py
  34. 1 1
      reflex/route.py
  35. 30 23
      reflex/state.py
  36. 3 1
      reflex/style.py
  37. 3 3
      reflex/testing.py
  38. 1 1
      reflex/utils/build.py
  39. 2 1
      reflex/utils/compat.py
  40. 2 2
      reflex/utils/exceptions.py
  41. 9 7
      reflex/utils/exec.py
  42. 2 2
      reflex/utils/format.py
  43. 7 1
      reflex/utils/lazy_loader.py
  44. 10 6
      reflex/utils/prerequisites.py
  45. 23 16
      reflex/utils/processes.py
  46. 8 6
      reflex/utils/pyi_generator.py
  47. 4 4
      reflex/utils/registry.py
  48. 2 2
      reflex/utils/telemetry.py
  49. 4 4
      reflex/utils/types.py
  50. 36 20
      reflex/vars/base.py
  51. 4 0
      reflex/vars/function.py
  52. 1 1
      reflex/vars/object.py
  53. 6 3
      reflex/vars/sequence.py
  54. 2 2
      scripts/wait_for_listening_port.py

+ 3 - 3
pyproject.toml

@@ -86,14 +86,14 @@ reportIncompatibleMethodOverride = false
 target-version = "py310"
 target-version = "py310"
 output-format = "concise"
 output-format = "concise"
 lint.isort.split-on-trailing-comma = false
 lint.isort.split-on-trailing-comma = false
-lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "N", "PERF", "PGH", "PTH", "RUF", "SIM", "T", "TRY", "W"]
+lint.select = ["ANN001","B", "C4", "D", "E", "ERA", "F", "FURB", "I", "N", "PERF", "PGH", "PTH", "RUF", "SIM", "T", "TRY", "W"]
 lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012", "TRY0"]
 lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012", "TRY0"]
 lint.pydocstyle.convention = "google"
 lint.pydocstyle.convention = "google"
 
 
 [tool.ruff.lint.per-file-ignores]
 [tool.ruff.lint.per-file-ignores]
 "__init__.py" = ["F401"]
 "__init__.py" = ["F401"]
-"tests/*.py" = ["D100", "D103", "D104", "B018", "PERF", "T", "N"]
-"benchmarks/*.py" = ["D100", "D103", "D104", "B018", "PERF", "T", "N"]
+"tests/*.py" = ["ANN001", "D100", "D103", "D104", "B018", "PERF", "T", "N"]
+"benchmarks/*.py" = ["ANN001", "D100", "D103", "D104", "B018", "PERF", "T", "N"]
 "reflex/.templates/*.py" = ["D100", "D103", "D104"]
 "reflex/.templates/*.py" = ["D100", "D103", "D104"]
 "*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N", "PGH"]
 "*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N", "PGH"]
 "pyi_generator.py" = ["N802"]
 "pyi_generator.py" = ["N802"]

+ 4 - 1
reflex/__init__.py

@@ -84,6 +84,9 @@ In the example above, you will be able to do `rx.list`
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
+from types import ModuleType
+from typing import Any
+
 from reflex.utils import (
 from reflex.utils import (
     compat,  # for side-effects
     compat,  # for side-effects
     lazy_loader,
     lazy_loader,
@@ -365,5 +368,5 @@ getattr, __dir__, __all__ = lazy_loader.attach(
 )
 )
 
 
 
 
-def __getattr__(name):
+def __getattr__(name: ModuleType | Any):
     return getattr(name)
     return getattr(name)

+ 18 - 19
reflex/app.py

@@ -408,15 +408,15 @@ class App(MiddlewareMixin, LifespanMixin):
         if self.api:
         if self.api:
 
 
             class HeaderMiddleware:
             class HeaderMiddleware:
-                def __init__(self, app):
+                def __init__(self, app: ASGIApp):
                     self.app = app
                     self.app = app
 
 
                 async def __call__(
                 async def __call__(
-                    self, scope: MutableMapping[str, Any], receive, send
+                    self, scope: MutableMapping[str, Any], receive: Any, send: Callable
                 ):
                 ):
                     original_send = send
                     original_send = send
 
 
-                    async def modified_send(message):
+                    async def modified_send(message: dict):
                         if message["type"] == "websocket.accept":
                         if message["type"] == "websocket.accept":
                             if scope.get("subprotocols"):
                             if scope.get("subprotocols"):
                                 # The following *does* say "subprotocol" instead of "subprotocols", intentionally.
                                 # The following *does* say "subprotocol" instead of "subprotocols", intentionally.
@@ -712,8 +712,8 @@ class App(MiddlewareMixin, LifespanMixin):
         Args:
         Args:
             component: The component to display at the page.
             component: The component to display at the page.
             title: The title of the page.
             title: The title of the page.
-            description: The description of the page.
             image: The image to display on the page.
             image: The image to display on the page.
+            description: The description of the page.
             on_load: The event handler(s) that will be called each time the page load.
             on_load: The event handler(s) that will be called each time the page load.
             meta: The metadata of the page.
             meta: The metadata of the page.
         """
         """
@@ -1056,7 +1056,7 @@ class App(MiddlewareMixin, LifespanMixin):
         with executor:
         with executor:
             result_futures = []
             result_futures = []
 
 
-            def _submit_work(fn, *args, **kwargs):
+            def _submit_work(fn: Callable, *args, **kwargs):
                 f = executor.submit(fn, *args, **kwargs)
                 f = executor.submit(fn, *args, **kwargs)
                 result_futures.append(f)
                 result_futures.append(f)
 
 
@@ -1387,15 +1387,14 @@ async def process(
                 if app._process_background(state, event) is not None:
                 if app._process_background(state, event) is not None:
                     # `final=True` allows the frontend send more events immediately.
                     # `final=True` allows the frontend send more events immediately.
                     yield StateUpdate(final=True)
                     yield StateUpdate(final=True)
-                    return
-
-                # Process the event synchronously.
-                async for update in state._process(event):
-                    # Postprocess the event.
-                    update = await app._postprocess(state, event, update)
-
-                    # Yield the update.
-                    yield update
+                else:
+                    # Process the event synchronously.
+                    async for update in state._process(event):
+                        # Postprocess the event.
+                        update = await app._postprocess(state, event, update)
+
+                        # Yield the update.
+                        yield update
     except Exception as ex:
     except Exception as ex:
         telemetry.send_error(ex, context="backend")
         telemetry.send_error(ex, context="backend")
 
 
@@ -1590,20 +1589,20 @@ class EventNamespace(AsyncNamespace):
         self.sid_to_token = {}
         self.sid_to_token = {}
         self.app = app
         self.app = app
 
 
-    def on_connect(self, sid, environ):
+    def on_connect(self, sid: str, environ: dict):
         """Event for when the websocket is connected.
         """Event for when the websocket is connected.
 
 
         Args:
         Args:
             sid: The Socket.IO session id.
             sid: The Socket.IO session id.
             environ: The request information, including HTTP headers.
             environ: The request information, including HTTP headers.
         """
         """
-        subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL", None)
+        subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL")
         if subprotocol and subprotocol != constants.Reflex.VERSION:
         if subprotocol and subprotocol != constants.Reflex.VERSION:
             console.warn(
             console.warn(
                 f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}."
                 f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}."
             )
             )
 
 
-    def on_disconnect(self, sid):
+    def on_disconnect(self, sid: str):
         """Event for when the websocket disconnects.
         """Event for when the websocket disconnects.
 
 
         Args:
         Args:
@@ -1625,7 +1624,7 @@ class EventNamespace(AsyncNamespace):
             self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
             self.emit(str(constants.SocketEvent.EVENT), update, to=sid)
         )
         )
 
 
-    async def on_event(self, sid, data):
+    async def on_event(self, sid: str, data: Any):
         """Event for receiving front-end websocket events.
         """Event for receiving front-end websocket events.
 
 
         Raises:
         Raises:
@@ -1692,7 +1691,7 @@ class EventNamespace(AsyncNamespace):
             # Emit the update from processing the event.
             # Emit the update from processing the event.
             await self.emit_update(update=update, sid=sid)
             await self.emit_update(update=update, sid=sid)
 
 
-    async def on_ping(self, sid):
+    async def on_ping(self, sid: str):
         """Event for testing the API endpoint.
         """Event for testing the API endpoint.
 
 
         Args:
         Args:

+ 1 - 1
reflex/app_mixins/lifespan.py

@@ -61,7 +61,7 @@ class LifespanMixin(AppMixin):
 
 
         Args:
         Args:
             task: The task to register.
             task: The task to register.
-            task_kwargs: The kwargs of the task.
+            **task_kwargs: The kwargs of the task.
 
 
         Raises:
         Raises:
             InvalidLifespanTaskTypeError: If the task is a generator function.
             InvalidLifespanTaskTypeError: If the task is a generator function.

+ 1 - 1
reflex/base.py

@@ -80,7 +80,7 @@ class Base(BaseModel):  # pyright: ignore [reportPossiblyUnboundVariable]
             default=serialize,
             default=serialize,
         )
         )
 
 
-    def set(self, **kwargs):
+    def set(self, **kwargs: Any):
         """Set multiple fields and return the object.
         """Set multiple fields and return the object.
 
 
         Args:
         Args:

+ 1 - 1
reflex/compiler/utils.py

@@ -502,7 +502,7 @@ def empty_dir(path: str | Path, keep_files: list[str] | None = None):
             path_ops.rm(element)
             path_ops.rm(element)
 
 
 
 
-def is_valid_url(url) -> bool:
+def is_valid_url(url: str) -> bool:
     """Check if a url is valid.
     """Check if a url is valid.
 
 
     Args:
     Args:

+ 5 - 5
reflex/components/component.py

@@ -426,7 +426,7 @@ class Component(BaseComponent, ABC):
             else:
             else:
                 continue
                 continue
 
 
-            def determine_key(value):
+            def determine_key(value: Any):
                 # Try to create a var from the value
                 # Try to create a var from the value
                 key = value if isinstance(value, Var) else LiteralVar.create(value)
                 key = value if isinstance(value, Var) else LiteralVar.create(value)
 
 
@@ -707,7 +707,7 @@ class Component(BaseComponent, ABC):
         # Filter out None props
         # Filter out None props
         props = {key: value for key, value in props.items() if value is not None}
         props = {key: value for key, value in props.items() if value is not None}
 
 
-        def validate_children(children):
+        def validate_children(children: tuple | list):
             for child in children:
             for child in children:
                 if isinstance(child, (tuple, list)):
                 if isinstance(child, (tuple, list)):
                     validate_children(child)
                     validate_children(child)
@@ -851,7 +851,7 @@ class Component(BaseComponent, ABC):
             else {}
             else {}
         )
         )
 
 
-    def render(self) -> Dict:
+    def render(self) -> dict:
         """Render the component.
         """Render the component.
 
 
         Returns:
         Returns:
@@ -869,7 +869,7 @@ class Component(BaseComponent, ABC):
         self._replace_prop_names(rendered_dict)
         self._replace_prop_names(rendered_dict)
         return rendered_dict
         return rendered_dict
 
 
-    def _replace_prop_names(self, rendered_dict) -> None:
+    def _replace_prop_names(self, rendered_dict: dict) -> None:
         """Replace the prop names in the render dictionary.
         """Replace the prop names in the render dictionary.
 
 
         Args:
         Args:
@@ -909,7 +909,7 @@ class Component(BaseComponent, ABC):
             comp.__name__ for comp in (Fragment, Foreach, Cond, Match)
             comp.__name__ for comp in (Fragment, Foreach, Cond, Match)
         ]
         ]
 
 
-        def validate_child(child):
+        def validate_child(child: Any):
             child_name = type(child).__name__
             child_name = type(child).__name__
 
 
             # Iterate through the immediate children of fragment
             # Iterate through the immediate children of fragment

+ 1 - 1
reflex/components/core/client_side_routing.py

@@ -41,7 +41,7 @@ class ClientSideRouting(Component):
         return ""
         return ""
 
 
 
 
-def wait_for_client_redirect(component) -> Component:
+def wait_for_client_redirect(component: Component) -> Component:
     """Wait for a redirect to occur before rendering a component.
     """Wait for a redirect to occur before rendering a component.
 
 
     This prevents the 404 page from flashing while the redirect is happening.
     This prevents the 404 page from flashing while the redirect is happening.

+ 1 - 1
reflex/components/core/client_side_routing.pyi

@@ -60,7 +60,7 @@ class ClientSideRouting(Component):
         """
         """
         ...
         ...
 
 
-def wait_for_client_redirect(component) -> Component: ...
+def wait_for_client_redirect(component: Component) -> Component: ...
 
 
 class Default404Page(Component):
 class Default404Page(Component):
     @overload
     @overload

+ 1 - 1
reflex/components/core/cond.py

@@ -153,7 +153,7 @@ def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var:
     if c2 is None:
     if c2 is None:
         raise ValueError("For conditional vars, the second argument must be set.")
         raise ValueError("For conditional vars, the second argument must be set.")
 
 
-    def create_var(cond_part):
+    def create_var(cond_part: Any) -> Var[Any]:
         return LiteralVar.create(cond_part)
         return LiteralVar.create(cond_part)
 
 
     # convert the truth and false cond parts into vars so the _var_data can be obtained.
     # convert the truth and false cond parts into vars so the _var_data can be obtained.

+ 1 - 1
reflex/components/core/match.py

@@ -109,7 +109,7 @@ class Match(MemoizationLeaf):
         return cases, default
         return cases, default
 
 
     @classmethod
     @classmethod
-    def _create_case_var_with_var_data(cls, case_element):
+    def _create_case_var_with_var_data(cls, case_element: Any) -> Var:
         """Convert a case element into a Var.If the case
         """Convert a case element into a Var.If the case
         is a Style type, we extract the var data and merge it with the
         is a Style type, we extract the var data and merge it with the
         newly created Var.
         newly created Var.

+ 2 - 4
reflex/components/datadisplay/logo.py

@@ -15,10 +15,8 @@ def svg_logo(color: Union[str, rx.Var[str]] = rx.color_mode_cond("#110F1F", "whi
         The Reflex logo SVG.
         The Reflex logo SVG.
     """
     """
 
 
-    def logo_path(d):
-        return rx.el.svg.path(
-            d=d,
-        )
+    def logo_path(d: str):
+        return rx.el.svg.path(d=d)
 
 
     paths = [
     paths = [
         "M0 11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 11.5999V7.1199H8.96V11.5999H6.72Z",
         "M0 11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 11.5999V7.1199H8.96V11.5999H6.72Z",

+ 1 - 1
reflex/components/el/element.py

@@ -6,7 +6,7 @@ from reflex.components.component import Component
 class Element(Component):
 class Element(Component):
     """The base class for all raw HTML elements."""
     """The base class for all raw HTML elements."""
 
 
-    def __eq__(self, other):
+    def __eq__(self, other: object):
         """Two elements are equal if they have the same tag.
         """Two elements are equal if they have the same tag.
 
 
         Args:
         Args:

+ 5 - 3
reflex/components/markdown/markdown.py

@@ -8,7 +8,7 @@ from functools import lru_cache
 from hashlib import md5
 from hashlib import md5
 from typing import Any, Callable, Dict, Sequence, Union
 from typing import Any, Callable, Dict, Sequence, Union
 
 
-from reflex.components.component import Component, CustomComponent
+from reflex.components.component import BaseComponent, Component, CustomComponent
 from reflex.components.tags.tag import Tag
 from reflex.components.tags.tag import Tag
 from reflex.utils import types
 from reflex.utils import types
 from reflex.utils.imports import ImportDict, ImportVar
 from reflex.utils.imports import ImportDict, ImportVar
@@ -379,7 +379,9 @@ const {_LANGUAGE!s} = match ? match[1] : '';
         # fallback to the default fn Var creation if the component is not a MarkdownComponentMap.
         # fallback to the default fn Var creation if the component is not a MarkdownComponentMap.
         return MarkdownComponentMap.create_map_fn_var(fn_body=formatted_component)
         return MarkdownComponentMap.create_map_fn_var(fn_body=formatted_component)
 
 
-    def _get_map_fn_custom_code_from_children(self, component) -> list[str]:
+    def _get_map_fn_custom_code_from_children(
+        self, component: BaseComponent
+    ) -> list[str]:
         """Recursively get markdown custom code from children components.
         """Recursively get markdown custom code from children components.
 
 
         Args:
         Args:
@@ -409,7 +411,7 @@ const {_LANGUAGE!s} = match ? match[1] : '';
         return custom_code_list
         return custom_code_list
 
 
     @staticmethod
     @staticmethod
-    def _component_map_hash(component_map) -> str:
+    def _component_map_hash(component_map: dict) -> str:
         inp = str(
         inp = str(
             {tag: component(_MOCK_ARG) for tag, component in component_map.items()}
             {tag: component(_MOCK_ARG) for tag, component in component_map.items()}
         ).encode()
         ).encode()

+ 3 - 1
reflex/components/next/image.py

@@ -1,5 +1,7 @@
 """Image component from next/image."""
 """Image component from next/image."""
 
 
+from __future__ import annotations
+
 from typing import Any, Literal, Optional, Union
 from typing import Any, Literal, Optional, Union
 
 
 from reflex.event import EventHandler, no_args_event_spec
 from reflex.event import EventHandler, no_args_event_spec
@@ -93,7 +95,7 @@ class Image(NextComponent):
 
 
         style = props.get("style", {})
         style = props.get("style", {})
 
 
-        def check_prop_type(prop_name, prop_value):
+        def check_prop_type(prop_name: str, prop_value: int | str | None):
             if types.check_prop_in_allowed_types(prop_value, allowed_types=[int]):
             if types.check_prop_in_allowed_types(prop_value, allowed_types=[int]):
                 props[prop_name] = prop_value
                 props[prop_name] = prop_value
 
 

+ 1 - 1
reflex/components/props.py

@@ -48,7 +48,7 @@ class PropsBase(Base):
 class NoExtrasAllowedProps(Base):
 class NoExtrasAllowedProps(Base):
     """A class that holds props to be passed or applied to a component with no extra props allowed."""
     """A class that holds props to be passed or applied to a component with no extra props allowed."""
 
 
-    def __init__(self, component_name=None, **kwargs):
+    def __init__(self, component_name: str | None = None, **kwargs):
         """Initialize the props.
         """Initialize the props.
 
 
         Args:
         Args:

+ 7 - 5
reflex/components/radix/themes/color_mode.py

@@ -17,7 +17,7 @@ rx.text(
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
-from typing import Dict, List, Literal, Optional, Union, get_args
+from typing import Any, Dict, List, Literal, Optional, Union, get_args
 
 
 from reflex.components.component import BaseComponent
 from reflex.components.component import BaseComponent
 from reflex.components.core.cond import Cond, color_mode_cond, cond
 from reflex.components.core.cond import Cond, color_mode_cond, cond
@@ -78,17 +78,19 @@ position_map: Dict[str, List[str]] = {
 
 
 
 
 # needed to inverse contains for find
 # needed to inverse contains for find
-def _find(const: List[str], var):
+def _find(const: List[str], var: Any):
     return LiteralArrayVar.create(const).contains(var)
     return LiteralArrayVar.create(const).contains(var)
 
 
 
 
-def _set_var_default(props, position, prop, default1, default2=""):
+def _set_var_default(
+    props: dict, position: Any, prop: str, default1: str, default2: str = ""
+):
     props.setdefault(
     props.setdefault(
         prop, cond(_find(position_map[prop], position), default1, default2)
         prop, cond(_find(position_map[prop], position), default1, default2)
     )
     )
 
 
 
 
-def _set_static_default(props, position, prop, default):
+def _set_static_default(props: dict, position: Any, prop: str, default: str):
     if prop in position:
     if prop in position:
         props.setdefault(prop, default)
         props.setdefault(prop, default)
 
 
@@ -142,7 +144,7 @@ class ColorModeIconButton(IconButton):
 
 
         if allow_system:
         if allow_system:
 
 
-            def color_mode_item(_color_mode):
+            def color_mode_item(_color_mode: str):
                 return dropdown_menu.item(
                 return dropdown_menu.item(
                     _color_mode.title(), on_click=set_color_mode(_color_mode)
                     _color_mode.title(), on_click=set_color_mode(_color_mode)
                 )
                 )

+ 1 - 1
reflex/components/radix/themes/layout/list.py

@@ -189,7 +189,7 @@ ordered_list = list_ns.ordered
 unordered_list = list_ns.unordered
 unordered_list = list_ns.unordered
 
 
 
 
-def __getattr__(name):
+def __getattr__(name: Any):
     # special case for when accessing list to avoid shadowing
     # special case for when accessing list to avoid shadowing
     # python's built in list object.
     # python's built in list object.
     if name == "list":
     if name == "list":

+ 1 - 1
reflex/components/recharts/charts.py

@@ -69,7 +69,7 @@ class ChartBase(RechartsCharts):
         )
         )
 
 
     @classmethod
     @classmethod
-    def create(cls, *children, **props) -> Component:
+    def create(cls, *children: Any, **props: Any) -> Component:
         """Create a chart component.
         """Create a chart component.
 
 
         Args:
         Args:

+ 10 - 10
reflex/components/sonner/toast.py

@@ -132,7 +132,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps):
     # Function that gets called when the toast disappears automatically after it's timeout (duration` prop).
     # Function that gets called when the toast disappears automatically after it's timeout (duration` prop).
     on_auto_close: Optional[Any]
     on_auto_close: Optional[Any]
 
 
-    def dict(self, *args, **kwargs) -> dict[str, Any]:
+    def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
         """Convert the object to a dictionary.
         """Convert the object to a dictionary.
 
 
         Args:
         Args:
@@ -276,12 +276,12 @@ class Toaster(Component):
         return run_script(toast)
         return run_script(toast)
 
 
     @staticmethod
     @staticmethod
-    def toast_info(message: str | Var = "", **kwargs):
+    def toast_info(message: str | Var = "", **kwargs: Any):
         """Display an info toast message.
         """Display an info toast message.
 
 
         Args:
         Args:
             message: The message to display.
             message: The message to display.
-            kwargs: Additional toast props.
+            **kwargs: Additional toast props.
 
 
         Returns:
         Returns:
             The toast event.
             The toast event.
@@ -289,12 +289,12 @@ class Toaster(Component):
         return Toaster.send_toast(message, level="info", **kwargs)
         return Toaster.send_toast(message, level="info", **kwargs)
 
 
     @staticmethod
     @staticmethod
-    def toast_warning(message: str | Var = "", **kwargs):
+    def toast_warning(message: str | Var = "", **kwargs: Any):
         """Display a warning toast message.
         """Display a warning toast message.
 
 
         Args:
         Args:
             message: The message to display.
             message: The message to display.
-            kwargs: Additional toast props.
+            **kwargs: Additional toast props.
 
 
         Returns:
         Returns:
             The toast event.
             The toast event.
@@ -302,12 +302,12 @@ class Toaster(Component):
         return Toaster.send_toast(message, level="warning", **kwargs)
         return Toaster.send_toast(message, level="warning", **kwargs)
 
 
     @staticmethod
     @staticmethod
-    def toast_error(message: str | Var = "", **kwargs):
+    def toast_error(message: str | Var = "", **kwargs: Any):
         """Display an error toast message.
         """Display an error toast message.
 
 
         Args:
         Args:
             message: The message to display.
             message: The message to display.
-            kwargs: Additional toast props.
+            **kwargs: Additional toast props.
 
 
         Returns:
         Returns:
             The toast event.
             The toast event.
@@ -315,12 +315,12 @@ class Toaster(Component):
         return Toaster.send_toast(message, level="error", **kwargs)
         return Toaster.send_toast(message, level="error", **kwargs)
 
 
     @staticmethod
     @staticmethod
-    def toast_success(message: str | Var = "", **kwargs):
+    def toast_success(message: str | Var = "", **kwargs: Any):
         """Display a success toast message.
         """Display a success toast message.
 
 
         Args:
         Args:
             message: The message to display.
             message: The message to display.
-            kwargs: Additional toast props.
+            **kwargs: Additional toast props.
 
 
         Returns:
         Returns:
             The toast event.
             The toast event.
@@ -352,7 +352,7 @@ class Toaster(Component):
         return run_script(dismiss_action)
         return run_script(dismiss_action)
 
 
     @classmethod
     @classmethod
-    def create(cls, *children, **props) -> Component:
+    def create(cls, *children: Any, **props: Any) -> Component:
         """Create a toaster component.
         """Create a toaster component.
 
 
         Args:
         Args:

+ 5 - 5
reflex/components/sonner/toast.pyi

@@ -51,7 +51,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps):
     on_dismiss: Optional[Any]
     on_dismiss: Optional[Any]
     on_auto_close: Optional[Any]
     on_auto_close: Optional[Any]
 
 
-    def dict(self, *args, **kwargs) -> dict[str, Any]: ...
+    def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ...
 
 
 class Toaster(Component):
 class Toaster(Component):
     is_used: ClassVar[bool] = False
     is_used: ClassVar[bool] = False
@@ -62,13 +62,13 @@ class Toaster(Component):
         message: str | Var = "", level: str | None = None, **props
         message: str | Var = "", level: str | None = None, **props
     ) -> EventSpec: ...
     ) -> EventSpec: ...
     @staticmethod
     @staticmethod
-    def toast_info(message: str | Var = "", **kwargs): ...
+    def toast_info(message: str | Var = "", **kwargs: Any): ...
     @staticmethod
     @staticmethod
-    def toast_warning(message: str | Var = "", **kwargs): ...
+    def toast_warning(message: str | Var = "", **kwargs: Any): ...
     @staticmethod
     @staticmethod
-    def toast_error(message: str | Var = "", **kwargs): ...
+    def toast_error(message: str | Var = "", **kwargs: Any): ...
     @staticmethod
     @staticmethod
-    def toast_success(message: str | Var = "", **kwargs): ...
+    def toast_success(message: str | Var = "", **kwargs: Any): ...
     @staticmethod
     @staticmethod
     def toast_dismiss(id: Var | str | None = None): ...
     def toast_dismiss(id: Var | str | None = None): ...
     @overload
     @overload

+ 6 - 4
reflex/components/suneditor/editor.py

@@ -3,7 +3,7 @@
 from __future__ import annotations
 from __future__ import annotations
 
 
 import enum
 import enum
-from typing import Dict, List, Literal, Optional, Tuple, Union
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union
 
 
 from reflex.base import Base
 from reflex.base import Base
 from reflex.components.component import Component, NoSSRComponent
 from reflex.components.component import Component, NoSSRComponent
@@ -115,7 +115,7 @@ class Editor(NoSSRComponent):
     # Alternatively to a string, a dict of your language can be passed to this prop.
     # Alternatively to a string, a dict of your language can be passed to this prop.
     # Please refer to the library docs for this.
     # Please refer to the library docs for this.
     # options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |
     # options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |
-    #  "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"
+    # "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"
     # default: "en".
     # default: "en".
     lang: Var[
     lang: Var[
         Union[
         Union[
@@ -244,11 +244,13 @@ class Editor(NoSSRComponent):
         }
         }
 
 
     @classmethod
     @classmethod
-    def create(cls, set_options: Optional[EditorOptions] = None, **props) -> Component:
+    def create(
+        cls, set_options: Optional[EditorOptions] = None, **props: Any
+    ) -> Component:
         """Create an instance of Editor. No children allowed.
         """Create an instance of Editor. No children allowed.
 
 
         Args:
         Args:
-            set_options(Optional[EditorOptions]): Configuration object to further configure the instance.
+            set_options: Configuration object to further configure the instance.
             **props: Any properties to be passed to the Editor
             **props: Any properties to be passed to the Editor
 
 
         Returns:
         Returns:

+ 2 - 2
reflex/components/suneditor/editor.pyi

@@ -171,8 +171,8 @@ class Editor(NoSSRComponent):
         """Create an instance of Editor. No children allowed.
         """Create an instance of Editor. No children allowed.
 
 
         Args:
         Args:
-            set_options(Optional[EditorOptions]): Configuration object to further configure the instance.
-            lang: Language of the editor.  Alternatively to a string, a dict of your language can be passed to this prop.  Please refer to the library docs for this.  options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |   "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"  default: "en".
+            set_options: Configuration object to further configure the instance.
+            lang: Language of the editor.  Alternatively to a string, a dict of your language can be passed to this prop.  Please refer to the library docs for this.  options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" |  "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it"  default: "en".
             name: This is used to set the HTML form name of the editor.  This means on HTML form submission,  it will be submitted together with contents of the editor by the name provided.
             name: This is used to set the HTML form name of the editor.  This means on HTML form submission,  it will be submitted together with contents of the editor by the name provided.
             default_value: Sets the default value of the editor.  This is useful if you don't want the on_change method to be called on render.  If you want the on_change method to be called on render please use the set_contents prop
             default_value: Sets the default value of the editor.  This is useful if you don't want the on_change method to be called on render.  If you want the on_change method to be called on render please use the set_contents prop
             width: Sets the width of the editor.  px and percentage values are accepted, eg width="100%" or width="500px"  default: 100%
             width: Sets the width of the editor.  px and percentage values are accepted, eg width="100%" or width="500px"  default: 100%

+ 1 - 1
reflex/components/tags/tag.py

@@ -49,7 +49,7 @@ class Tag:
         """Set the tag's fields.
         """Set the tag's fields.
 
 
         Args:
         Args:
-            kwargs: The fields to set.
+            **kwargs: The fields to set.
 
 
         Returns:
         Returns:
             The tag with the fields
             The tag with the fields

+ 3 - 3
reflex/config.py

@@ -407,7 +407,7 @@ class env_var:  # noqa: N801 # pyright: ignore [reportRedeclaration]
         self.default = default
         self.default = default
         self.internal = internal
         self.internal = internal
 
 
-    def __set_name__(self, owner, name):
+    def __set_name__(self, owner: Any, name: str):
         """Set the name of the descriptor.
         """Set the name of the descriptor.
 
 
         Args:
         Args:
@@ -416,7 +416,7 @@ class env_var:  # noqa: N801 # pyright: ignore [reportRedeclaration]
         """
         """
         self.name = name
         self.name = name
 
 
-    def __get__(self, instance, owner):
+    def __get__(self, instance: Any, owner: Any):
         """Get the EnvVar instance.
         """Get the EnvVar instance.
 
 
         Args:
         Args:
@@ -435,7 +435,7 @@ class env_var:  # noqa: N801 # pyright: ignore [reportRedeclaration]
 
 
 if TYPE_CHECKING:
 if TYPE_CHECKING:
 
 
-    def env_var(default, internal=False) -> EnvVar:
+    def env_var(default: Any, internal: bool = False) -> EnvVar:
         """Typing helper for the env_var descriptor.
         """Typing helper for the env_var descriptor.
 
 
         Args:
         Args:

+ 1 - 1
reflex/custom_components/custom_components.py

@@ -83,7 +83,7 @@ def _get_package_config(exit_on_fail: bool = True) -> dict:
         The package configuration.
         The package configuration.
 
 
     Raises:
     Raises:
-        Exit: If the pyproject.toml file is not found.
+        Exit: If the pyproject.toml file is not found and exit_on_fail is True.
     """
     """
     pyproject = Path(CustomComponents.PYPROJECT_TOML)
     pyproject = Path(CustomComponents.PYPROJECT_TOML)
     try:
     try:

+ 7 - 6
reflex/event.py

@@ -1075,7 +1075,8 @@ def download(
     )
     )
 
 
 
 
-def _callback_arg_spec(eval_result):
+# This function seems unused. Check if we still need it. If not, remove in 0.7.0
+def _callback_arg_spec(eval_result: Any):
     """ArgSpec for call_script callback function.
     """ArgSpec for call_script callback function.
 
 
     Args:
     Args:
@@ -1180,7 +1181,7 @@ def run_script(
     return call_function(ArgsFunctionOperation.create((), javascript_code), callback)
     return call_function(ArgsFunctionOperation.create((), javascript_code), callback)
 
 
 
 
-def get_event(state, event):
+def get_event(state: BaseState, event: str):
     """Get the event from the given state.
     """Get the event from the given state.
 
 
     Args:
     Args:
@@ -1193,7 +1194,7 @@ def get_event(state, event):
     return f"{state.get_name()}.{event}"
     return f"{state.get_name()}.{event}"
 
 
 
 
-def get_hydrate_event(state) -> str:
+def get_hydrate_event(state: BaseState) -> str:
     """Get the name of the hydrate event for the state.
     """Get the name of the hydrate event for the state.
 
 
     Args:
     Args:
@@ -1832,13 +1833,13 @@ class EventCallback(Generic[P, T]):
 
 
     @overload
     @overload
     def __get__(
     def __get__(
-        self: EventCallback[P, T], instance: None, owner
+        self: EventCallback[P, T], instance: None, owner: Any
     ) -> EventCallback[P, T]: ...
     ) -> EventCallback[P, T]: ...
 
 
     @overload
     @overload
-    def __get__(self, instance, owner) -> Callable[P, T]: ...
+    def __get__(self, instance: Any, owner: Any) -> Callable[P, T]: ...
 
 
-    def __get__(self, instance, owner) -> Callable:
+    def __get__(self, instance: Any, owner: Any) -> Callable:
         """Get the function with the instance bound to it.
         """Get the function with the instance bound to it.
 
 
         Args:
         Args:

+ 5 - 5
reflex/experimental/hooks.py

@@ -11,7 +11,7 @@ def _compose_react_imports(tags: list[str]) -> dict[str, list[ImportVar]]:
     return {"react": [ImportVar(tag=tag) for tag in tags]}
     return {"react": [ImportVar(tag=tag) for tag in tags]}
 
 
 
 
-def const(name, value) -> Var:
+def const(name: str | list[str], value: str | Var) -> Var:
     """Create a constant Var.
     """Create a constant Var.
 
 
     Args:
     Args:
@@ -26,7 +26,7 @@ def const(name, value) -> Var:
     return Var(_js_expr=f"const {name} = {value}")
     return Var(_js_expr=f"const {name} = {value}")
 
 
 
 
-def useCallback(func, deps) -> Var:  # noqa: N802
+def useCallback(func: str, deps: list) -> Var:  # noqa: N802
     """Create a useCallback hook with a function and dependencies.
     """Create a useCallback hook with a function and dependencies.
 
 
     Args:
     Args:
@@ -42,7 +42,7 @@ def useCallback(func, deps) -> Var:  # noqa: N802
     )
     )
 
 
 
 
-def useContext(context) -> Var:  # noqa: N802
+def useContext(context: str) -> Var:  # noqa: N802
     """Create a useContext hook with a context.
     """Create a useContext hook with a context.
 
 
     Args:
     Args:
@@ -57,7 +57,7 @@ def useContext(context) -> Var:  # noqa: N802
     )
     )
 
 
 
 
-def useRef(default) -> Var:  # noqa: N802
+def useRef(default: str) -> Var:  # noqa: N802
     """Create a useRef hook with a default value.
     """Create a useRef hook with a default value.
 
 
     Args:
     Args:
@@ -72,7 +72,7 @@ def useRef(default) -> Var:  # noqa: N802
     )
     )
 
 
 
 
-def useState(var_name, default=None) -> Var:  # noqa: N802
+def useState(var_name: str, default: str | None = None) -> Var:  # noqa: N802
     """Create a useState hook with a variable name and setter name.
     """Create a useState hook with a variable name and setter name.
 
 
     Args:
     Args:

+ 3 - 3
reflex/experimental/misc.py

@@ -1,16 +1,16 @@
 """Miscellaneous functions for the experimental package."""
 """Miscellaneous functions for the experimental package."""
 
 
 import asyncio
 import asyncio
-from typing import Any
+from typing import Any, Callable
 
 
 
 
-async def run_in_thread(func) -> Any:
+async def run_in_thread(func: Callable) -> Any:
     """Run a function in a separate thread.
     """Run a function in a separate thread.
 
 
     To not block the UI event queue, run_in_thread must be inside inside a rx.event(background=True) decorated method.
     To not block the UI event queue, run_in_thread must be inside inside a rx.event(background=True) decorated method.
 
 
     Args:
     Args:
-        func (callable): The non-async function to run.
+        func: The non-async function to run.
 
 
     Raises:
     Raises:
         ValueError: If the function is an async function.
         ValueError: If the function is an async function.

+ 1 - 1
reflex/istate/wrappers.py

@@ -6,7 +6,7 @@ from reflex.istate.proxy import ReadOnlyStateProxy
 from reflex.state import _split_substate_key, _substate_key, get_state_manager
 from reflex.state import _split_substate_key, _substate_key, get_state_manager
 
 
 
 
-async def get_state(token, state_cls: Any | None = None) -> ReadOnlyStateProxy:
+async def get_state(token: str, state_cls: Any | None = None) -> ReadOnlyStateProxy:
     """Get the instance of a state for a token.
     """Get the instance of a state for a token.
 
 
     Args:
     Args:

+ 9 - 4
reflex/model.py

@@ -18,6 +18,7 @@ import sqlalchemy
 import sqlalchemy.exc
 import sqlalchemy.exc
 import sqlalchemy.ext.asyncio
 import sqlalchemy.ext.asyncio
 import sqlalchemy.orm
 import sqlalchemy.orm
+from alembic.runtime.migration import MigrationContext
 
 
 from reflex.base import Base
 from reflex.base import Base
 from reflex.config import environment, get_config
 from reflex.config import environment, get_config
@@ -261,7 +262,7 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
         super().__init_subclass__()
         super().__init_subclass__()
 
 
     @classmethod
     @classmethod
-    def _dict_recursive(cls, value):
+    def _dict_recursive(cls, value: Any):
         """Recursively serialize the relationship object(s).
         """Recursively serialize the relationship object(s).
 
 
         Args:
         Args:
@@ -393,7 +394,11 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
         writer = alembic.autogenerate.rewriter.Rewriter()
         writer = alembic.autogenerate.rewriter.Rewriter()
 
 
         @writer.rewrites(alembic.operations.ops.AddColumnOp)
         @writer.rewrites(alembic.operations.ops.AddColumnOp)
-        def render_add_column_with_server_default(context, revision, op):
+        def render_add_column_with_server_default(
+            context: MigrationContext,
+            revision: str | None,
+            op: Any,
+        ):
             # Carry the sqlmodel default as server_default so that newly added
             # Carry the sqlmodel default as server_default so that newly added
             # columns get the desired default value in existing rows.
             # columns get the desired default value in existing rows.
             if op.column.default is not None and op.column.server_default is None:
             if op.column.default is not None and op.column.server_default is None:
@@ -402,7 +407,7 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
                 )
                 )
             return op
             return op
 
 
-        def run_autogenerate(rev, context):
+        def run_autogenerate(rev: str, context: MigrationContext):
             revision_context.run_autogenerate(rev, context)
             revision_context.run_autogenerate(rev, context)
             return []
             return []
 
 
@@ -444,7 +449,7 @@ class Model(Base, sqlmodel.SQLModel):  # pyright: ignore [reportGeneralTypeIssue
         """
         """
         config, script_directory = cls._alembic_config()
         config, script_directory = cls._alembic_config()
 
 
-        def run_upgrade(rev, context):
+        def run_upgrade(rev: str, context: MigrationContext):
             return script_directory._upgrade_revs(to_rev, rev)
             return script_directory._upgrade_revs(to_rev, rev)
 
 
         with alembic.runtime.environment.EnvironmentContext(
         with alembic.runtime.environment.EnvironmentContext(

+ 3 - 3
reflex/page.py

@@ -3,7 +3,7 @@
 from __future__ import annotations
 from __future__ import annotations
 
 
 from collections import defaultdict
 from collections import defaultdict
-from typing import Any, Dict, List
+from typing import Any, Callable, Dict, List
 
 
 from reflex.config import get_config
 from reflex.config import get_config
 from reflex.event import BASE_STATE, EventType
 from reflex.event import BASE_STATE, EventType
@@ -42,7 +42,7 @@ def page(
         The decorated function.
         The decorated function.
     """
     """
 
 
-    def decorator(render_fn):
+    def decorator(render_fn: Callable):
         kwargs = {}
         kwargs = {}
         if route:
         if route:
             kwargs["route"] = route
             kwargs["route"] = route
@@ -66,7 +66,7 @@ def page(
     return decorator
     return decorator
 
 
 
 
-def get_decorated_pages(omit_implicit_routes=True) -> list[dict[str, Any]]:
+def get_decorated_pages(omit_implicit_routes: bool = True) -> list[dict[str, Any]]:
     """Get the decorated pages.
     """Get the decorated pages.
 
 
     Args:
     Args:

+ 12 - 8
reflex/reflex.py

@@ -125,8 +125,8 @@ def _run(
     env: constants.Env = constants.Env.DEV,
     env: constants.Env = constants.Env.DEV,
     frontend: bool = True,
     frontend: bool = True,
     backend: bool = True,
     backend: bool = True,
-    frontend_port: str = str(config.frontend_port),
-    backend_port: str = str(config.backend_port),
+    frontend_port: int = config.frontend_port,
+    backend_port: int = config.backend_port,
     backend_host: str = config.backend_host,
     backend_host: str = config.backend_host,
     loglevel: constants.LogLevel = config.loglevel,
     loglevel: constants.LogLevel = config.loglevel,
 ):
 ):
@@ -160,18 +160,22 @@ def _run(
     # Find the next available open port if applicable.
     # Find the next available open port if applicable.
     if frontend:
     if frontend:
         frontend_port = processes.handle_port(
         frontend_port = processes.handle_port(
-            "frontend", frontend_port, str(constants.DefaultPorts.FRONTEND_PORT)
+            "frontend",
+            frontend_port,
+            constants.DefaultPorts.FRONTEND_PORT,
         )
         )
 
 
     if backend:
     if backend:
         backend_port = processes.handle_port(
         backend_port = processes.handle_port(
-            "backend", backend_port, str(constants.DefaultPorts.BACKEND_PORT)
+            "backend",
+            backend_port,
+            constants.DefaultPorts.BACKEND_PORT,
         )
         )
 
 
     # Apply the new ports to the config.
     # Apply the new ports to the config.
-    if frontend_port != str(config.frontend_port):
+    if frontend_port != config.frontend_port:
         config._set_persistent(frontend_port=frontend_port)
         config._set_persistent(frontend_port=frontend_port)
-    if backend_port != str(config.backend_port):
+    if backend_port != config.backend_port:
         config._set_persistent(backend_port=backend_port)
         config._set_persistent(backend_port=backend_port)
 
 
     # Reload the config to make sure the env vars are persistent.
     # Reload the config to make sure the env vars are persistent.
@@ -262,10 +266,10 @@ def run(
         help="Execute only backend.",
         help="Execute only backend.",
         envvar=environment.REFLEX_BACKEND_ONLY.name,
         envvar=environment.REFLEX_BACKEND_ONLY.name,
     ),
     ),
-    frontend_port: str = typer.Option(
+    frontend_port: int = typer.Option(
         config.frontend_port, help="Specify a different frontend port."
         config.frontend_port, help="Specify a different frontend port."
     ),
     ),
-    backend_port: str = typer.Option(
+    backend_port: int = typer.Option(
         config.backend_port, help="Specify a different backend port."
         config.backend_port, help="Specify a different backend port."
     ),
     ),
     backend_host: str = typer.Option(
     backend_host: str = typer.Option(

+ 1 - 1
reflex/route.py

@@ -103,7 +103,7 @@ def catchall_prefix(route: str) -> str:
     return route.replace(pattern, "") if pattern else ""
     return route.replace(pattern, "") if pattern else ""
 
 
 
 
-def replace_brackets_with_keywords(input_string):
+def replace_brackets_with_keywords(input_string: str) -> str:
     """Replace brackets and everything inside it in a string with a keyword.
     """Replace brackets and everything inside it in a string with a keyword.
 
 
     Args:
     Args:

+ 30 - 23
reflex/state.py

@@ -31,6 +31,7 @@ from typing import (
     Optional,
     Optional,
     Sequence,
     Sequence,
     Set,
     Set,
+    SupportsIndex,
     Tuple,
     Tuple,
     Type,
     Type,
     TypeVar,
     TypeVar,
@@ -1058,7 +1059,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
         setattr(cls, prop._var_field_name, prop)
         setattr(cls, prop._var_field_name, prop)
 
 
     @classmethod
     @classmethod
-    def _create_event_handler(cls, fn):
+    def _create_event_handler(cls, fn: Any):
         """Create an event handler for the given function.
         """Create an event handler for the given function.
 
 
         Args:
         Args:
@@ -1176,14 +1177,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
 
 
         cls._check_overwritten_dynamic_args(list(args.keys()))
         cls._check_overwritten_dynamic_args(list(args.keys()))
 
 
-        def argsingle_factory(param):
-            def inner_func(self) -> str:
+        def argsingle_factory(param: str):
+            def inner_func(self: BaseState) -> str:
                 return self.router.page.params.get(param, "")
                 return self.router.page.params.get(param, "")
 
 
             return inner_func
             return inner_func
 
 
-        def arglist_factory(param):
-            def inner_func(self) -> List[str]:
+        def arglist_factory(param: str):
+            def inner_func(self: BaseState) -> List[str]:
                 return self.router.page.params.get(param, [])
                 return self.router.page.params.get(param, [])
 
 
             return inner_func
             return inner_func
@@ -2594,7 +2595,9 @@ class StateProxy(wrapt.ObjectProxy):
     """
     """
 
 
     def __init__(
     def __init__(
-        self, state_instance, parent_state_proxy: Optional["StateProxy"] = None
+        self,
+        state_instance: BaseState,
+        parent_state_proxy: Optional["StateProxy"] = None,
     ):
     ):
         """Create a proxy for a state instance.
         """Create a proxy for a state instance.
 
 
@@ -3540,7 +3543,9 @@ class StateManagerRedis(StateManager):
 
 
     @validator("lock_warning_threshold")
     @validator("lock_warning_threshold")
     @classmethod
     @classmethod
-    def validate_lock_warning_threshold(cls, lock_warning_threshold: int, values):
+    def validate_lock_warning_threshold(
+        cls, lock_warning_threshold: int, values: dict[str, int]
+    ):
         """Validate the lock warning threshold.
         """Validate the lock warning threshold.
 
 
         Args:
         Args:
@@ -3808,10 +3813,10 @@ class MutableProxy(wrapt.ObjectProxy):
 
 
     def _mark_dirty(
     def _mark_dirty(
         self,
         self,
-        wrapped=None,
-        instance=None,
-        args=(),
-        kwargs=None,
+        wrapped: Callable | None = None,
+        instance: BaseState | None = None,
+        args: tuple = (),
+        kwargs: dict | None = None,
     ) -> Any:
     ) -> Any:
         """Mark the state as dirty, then call a wrapped function.
         """Mark the state as dirty, then call a wrapped function.
 
 
@@ -3885,7 +3890,9 @@ class MutableProxy(wrapt.ObjectProxy):
             )
             )
         return value
         return value
 
 
-    def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any:
+    def _wrap_recursive_decorator(
+        self, wrapped: Callable, instance: BaseState, args: list, kwargs: dict
+    ) -> Any:
         """Wrap a function that returns a possibly mutable value.
         """Wrap a function that returns a possibly mutable value.
 
 
         Intended for use with `FunctionWrapper` from the `wrapt` library.
         Intended for use with `FunctionWrapper` from the `wrapt` library.
@@ -3944,7 +3951,7 @@ class MutableProxy(wrapt.ObjectProxy):
 
 
         return value
         return value
 
 
-    def __getitem__(self, key) -> Any:
+    def __getitem__(self, key: Any) -> Any:
         """Get the item on the proxied object and return a proxy if mutable.
         """Get the item on the proxied object and return a proxy if mutable.
 
 
         Args:
         Args:
@@ -3967,7 +3974,7 @@ class MutableProxy(wrapt.ObjectProxy):
             # Recursively wrap mutable items retrieved through this proxy.
             # Recursively wrap mutable items retrieved through this proxy.
             yield self._wrap_recursive(value)
             yield self._wrap_recursive(value)
 
 
-    def __delattr__(self, name):
+    def __delattr__(self, name: str):
         """Delete the attribute on the proxied object and mark state dirty.
         """Delete the attribute on the proxied object and mark state dirty.
 
 
         Args:
         Args:
@@ -3975,7 +3982,7 @@ class MutableProxy(wrapt.ObjectProxy):
         """
         """
         self._mark_dirty(super().__delattr__, args=(name,))
         self._mark_dirty(super().__delattr__, args=(name,))
 
 
-    def __delitem__(self, key):
+    def __delitem__(self, key: str):
         """Delete the item on the proxied object and mark state dirty.
         """Delete the item on the proxied object and mark state dirty.
 
 
         Args:
         Args:
@@ -3983,7 +3990,7 @@ class MutableProxy(wrapt.ObjectProxy):
         """
         """
         self._mark_dirty(super().__delitem__, args=(key,))
         self._mark_dirty(super().__delitem__, args=(key,))
 
 
-    def __setitem__(self, key, value):
+    def __setitem__(self, key: str, value: Any):
         """Set the item on the proxied object and mark state dirty.
         """Set the item on the proxied object and mark state dirty.
 
 
         Args:
         Args:
@@ -3992,7 +3999,7 @@ class MutableProxy(wrapt.ObjectProxy):
         """
         """
         self._mark_dirty(super().__setitem__, args=(key, value))
         self._mark_dirty(super().__setitem__, args=(key, value))
 
 
-    def __setattr__(self, name, value):
+    def __setattr__(self, name: str, value: Any):
         """Set the attribute on the proxied object and mark state dirty.
         """Set the attribute on the proxied object and mark state dirty.
 
 
         If the attribute starts with "_self_", then the state is NOT marked
         If the attribute starts with "_self_", then the state is NOT marked
@@ -4016,7 +4023,7 @@ class MutableProxy(wrapt.ObjectProxy):
         """
         """
         return copy.copy(self.__wrapped__)
         return copy.copy(self.__wrapped__)
 
 
-    def __deepcopy__(self, memo=None) -> Any:
+    def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Any:
         """Return a deepcopy of the proxy.
         """Return a deepcopy of the proxy.
 
 
         Args:
         Args:
@@ -4027,7 +4034,7 @@ class MutableProxy(wrapt.ObjectProxy):
         """
         """
         return copy.deepcopy(self.__wrapped__, memo=memo)
         return copy.deepcopy(self.__wrapped__, memo=memo)
 
 
-    def __reduce_ex__(self, protocol_version):
+    def __reduce_ex__(self, protocol_version: SupportsIndex):
         """Get the state for redis serialization.
         """Get the state for redis serialization.
 
 
         This method is called by cloudpickle to serialize the object.
         This method is called by cloudpickle to serialize the object.
@@ -4091,10 +4098,10 @@ class ImmutableMutableProxy(MutableProxy):
 
 
     def _mark_dirty(
     def _mark_dirty(
         self,
         self,
-        wrapped=None,
-        instance=None,
-        args=(),
-        kwargs=None,
+        wrapped: Callable | None = None,
+        instance: BaseState | None = None,
+        args: tuple = (),
+        kwargs: dict | None = None,
     ) -> Any:
     ) -> Any:
         """Raise an exception when an attempt is made to modify the object.
         """Raise an exception when an attempt is made to modify the object.
 
 

+ 3 - 1
reflex/style.py

@@ -182,7 +182,9 @@ def convert(
     var_data = None  # Track import/hook data from any Vars in the style dict.
     var_data = None  # Track import/hook data from any Vars in the style dict.
     out = {}
     out = {}
 
 
-    def update_out_dict(return_value, keys_to_update):
+    def update_out_dict(
+        return_value: Var | dict | list | str, keys_to_update: tuple[str, ...]
+    ):
         for k in keys_to_update:
         for k in keys_to_update:
             out[k] = return_value
             out[k] = return_value
 
 

+ 3 - 3
reflex/testing.py

@@ -90,7 +90,7 @@ else:
 class chdir(contextlib.AbstractContextManager):  # noqa: N801
 class chdir(contextlib.AbstractContextManager):  # noqa: N801
     """Non thread-safe context manager to change the current working directory."""
     """Non thread-safe context manager to change the current working directory."""
 
 
-    def __init__(self, path):
+    def __init__(self, path: str | Path):
         """Prepare contextmanager.
         """Prepare contextmanager.
 
 
         Args:
         Args:
@@ -327,7 +327,7 @@ class AppHarness:
 
 
         return _shutdown_redis
         return _shutdown_redis
 
 
-    def _start_backend(self, port=0):
+    def _start_backend(self, port: int = 0):
         if self.app_instance is None or self.app_instance.api is None:
         if self.app_instance is None or self.app_instance.api is None:
             raise RuntimeError("App was not initialized.")
             raise RuntimeError("App was not initialized.")
         self.backend = uvicorn.Server(
         self.backend = uvicorn.Server(
@@ -430,7 +430,7 @@ class AppHarness:
         return self
         return self
 
 
     @staticmethod
     @staticmethod
-    def get_app_global_source(key, value):
+    def get_app_global_source(key: str, value: Any):
         """Get the source code of a global object.
         """Get the source code of a global object.
         If value is a function or class we render the actual
         If value is a function or class we render the actual
         source of value otherwise we assign value to key.
         source of value otherwise we assign value to key.

+ 1 - 1
reflex/utils/build.py

@@ -27,7 +27,7 @@ def set_env_json():
     )
     )
 
 
 
 
-def generate_sitemap_config(deploy_url: str, export=False):
+def generate_sitemap_config(deploy_url: str, export: bool = False):
     """Generate the sitemap config file.
     """Generate the sitemap config file.
 
 
     Args:
     Args:

+ 2 - 1
reflex/utils/compat.py

@@ -2,6 +2,7 @@
 
 
 import contextlib
 import contextlib
 import sys
 import sys
+from typing import Any
 
 
 
 
 async def windows_hot_reload_lifespan_hack():
 async def windows_hot_reload_lifespan_hack():
@@ -74,7 +75,7 @@ with pydantic_v1_patch():
     import sqlmodel as sqlmodel
     import sqlmodel as sqlmodel
 
 
 
 
-def sqlmodel_field_has_primary_key(field) -> bool:
+def sqlmodel_field_has_primary_key(field: Any) -> bool:
     """Determines if a field is a priamary.
     """Determines if a field is a priamary.
 
 
     Args:
     Args:

+ 2 - 2
reflex/utils/exceptions.py

@@ -78,7 +78,7 @@ class VarAttributeError(ReflexError, AttributeError):
 class UntypedComputedVarError(ReflexError, TypeError):
 class UntypedComputedVarError(ReflexError, TypeError):
     """Custom TypeError for untyped computed var errors."""
     """Custom TypeError for untyped computed var errors."""
 
 
-    def __init__(self, var_name):
+    def __init__(self, var_name: str):
         """Initialize the UntypedComputedVarError.
         """Initialize the UntypedComputedVarError.
 
 
         Args:
         Args:
@@ -90,7 +90,7 @@ class UntypedComputedVarError(ReflexError, TypeError):
 class MissingAnnotationError(ReflexError, TypeError):
 class MissingAnnotationError(ReflexError, TypeError):
     """Custom TypeError for missing annotations."""
     """Custom TypeError for missing annotations."""
 
 
-    def __init__(self, var_name):
+    def __init__(self, var_name: str):
         """Initialize the MissingAnnotationError.
         """Initialize the MissingAnnotationError.
 
 
         Args:
         Args:

+ 9 - 7
reflex/utils/exec.py

@@ -71,7 +71,9 @@ def notify_backend():
 # run_process_and_launch_url is assumed to be used
 # run_process_and_launch_url is assumed to be used
 # only to launch the frontend
 # only to launch the frontend
 # If this is not the case, might have to change the logic
 # If this is not the case, might have to change the logic
-def run_process_and_launch_url(run_command: list[str | None], backend_present=True):
+def run_process_and_launch_url(
+    run_command: list[str | None], backend_present: bool = True
+):
     """Run the process and launch the URL.
     """Run the process and launch the URL.
 
 
     Args:
     Args:
@@ -134,7 +136,7 @@ def run_process_and_launch_url(run_command: list[str | None], backend_present=Tr
             break  # while True
             break  # while True
 
 
 
 
-def run_frontend(root: Path, port: str, backend_present=True):
+def run_frontend(root: Path, port: str, backend_present: bool = True):
     """Run the frontend.
     """Run the frontend.
 
 
     Args:
     Args:
@@ -156,7 +158,7 @@ def run_frontend(root: Path, port: str, backend_present=True):
     )
     )
 
 
 
 
-def run_frontend_prod(root: Path, port: str, backend_present=True):
+def run_frontend_prod(root: Path, port: str, backend_present: bool = True):
     """Run the frontend.
     """Run the frontend.
 
 
     Args:
     Args:
@@ -265,7 +267,7 @@ def get_reload_dirs() -> list[Path]:
     return reload_dirs
     return reload_dirs
 
 
 
 
-def run_uvicorn_backend(host, port, loglevel: LogLevel):
+def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
     """Run the backend in development mode using Uvicorn.
     """Run the backend in development mode using Uvicorn.
 
 
     Args:
     Args:
@@ -285,7 +287,7 @@ def run_uvicorn_backend(host, port, loglevel: LogLevel):
     )
     )
 
 
 
 
-def run_granian_backend(host, port, loglevel: LogLevel):
+def run_granian_backend(host: str, port: int, loglevel: LogLevel):
     """Run the backend in development mode using Granian.
     """Run the backend in development mode using Granian.
 
 
     Args:
     Args:
@@ -352,7 +354,7 @@ def run_backend_prod(
         run_uvicorn_backend_prod(host, port, loglevel)
         run_uvicorn_backend_prod(host, port, loglevel)
 
 
 
 
-def run_uvicorn_backend_prod(host, port, loglevel):
+def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
     """Run the backend in production mode using Uvicorn.
     """Run the backend in production mode using Uvicorn.
 
 
     Args:
     Args:
@@ -404,7 +406,7 @@ def run_uvicorn_backend_prod(host, port, loglevel):
     )
     )
 
 
 
 
-def run_granian_backend_prod(host, port, loglevel):
+def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
     """Run the backend in production mode using Granian.
     """Run the backend in production mode using Granian.
 
 
     Args:
     Args:

+ 2 - 2
reflex/utils/format.py

@@ -220,7 +220,7 @@ def _escape_js_string(string: str) -> str:
     """
     """
 
 
     # TODO: we may need to re-vist this logic after new Var API is implemented.
     # TODO: we may need to re-vist this logic after new Var API is implemented.
-    def escape_outside_segments(segment):
+    def escape_outside_segments(segment: str):
         """Escape backticks in segments outside of `${}`.
         """Escape backticks in segments outside of `${}`.
 
 
         Args:
         Args:
@@ -283,7 +283,7 @@ def format_var(var: Var) -> str:
     return str(var)
     return str(var)
 
 
 
 
-def format_route(route: str, format_case=True) -> str:
+def format_route(route: str, format_case: bool = True) -> str:
     """Format the given route.
     """Format the given route.
 
 
     Args:
     Args:

+ 7 - 1
reflex/utils/lazy_loader.py

@@ -1,11 +1,17 @@
 """Module to implement lazy loading in reflex."""
 """Module to implement lazy loading in reflex."""
 
 
+from __future__ import annotations
+
 import copy
 import copy
 
 
 import lazy_loader as lazy
 import lazy_loader as lazy
 
 
 
 
-def attach(package_name, submodules=None, submod_attrs=None):
+def attach(
+    package_name: str,
+    submodules: set | None = None,
+    submod_attrs: dict | None = None,
+):
     """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach.
     """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach.
     The lazy loader __getattr__ doesn't support tuples as list values. We needed to add
     The lazy loader __getattr__ doesn't support tuples as list values. We needed to add
     this functionality (tuples) in Reflex to support 'import as _' statements. This function
     this functionality (tuples) in Reflex to support 'import as _' statements. This function

+ 10 - 6
reflex/utils/prerequisites.py

@@ -884,7 +884,9 @@ def init_reflex_json(project_hash: int | None):
     path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
     path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
 
 
 
 
-def update_next_config(export=False, transpile_packages: Optional[List[str]] = None):
+def update_next_config(
+    export: bool = False, transpile_packages: Optional[List[str]] = None
+):
     """Update Next.js config from Reflex config.
     """Update Next.js config from Reflex config.
 
 
     Args:
     Args:
@@ -1128,7 +1130,7 @@ def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
         The decorated function.
         The decorated function.
     """
     """
 
 
-    def _inner_decorator(func):
+    def _inner_decorator(func: Callable):
         def _inner(*args, **kwargs):
         def _inner(*args, **kwargs):
             payload = _read_cached_procedure_file(cache_file)
             payload = _read_cached_procedure_file(cache_file)
             new_payload = payload_fn(*args, **kwargs)
             new_payload = payload_fn(*args, **kwargs)
@@ -1310,7 +1312,7 @@ def validate_bun():
             raise typer.Exit(1)
             raise typer.Exit(1)
 
 
 
 
-def validate_frontend_dependencies(init=True):
+def validate_frontend_dependencies(init: bool = True):
     """Validate frontend dependencies to ensure they meet requirements.
     """Validate frontend dependencies to ensure they meet requirements.
 
 
     Args:
     Args:
@@ -1634,7 +1636,9 @@ def initialize_default_app(app_name: str):
     initialize_app_directory(app_name)
     initialize_app_directory(app_name)
 
 
 
 
-def validate_and_create_app_using_remote_template(app_name, template, templates):
+def validate_and_create_app_using_remote_template(
+    app_name: str, template: str, templates: dict[str, Template]
+):
     """Validate and create an app using a remote template.
     """Validate and create an app using a remote template.
 
 
     Args:
     Args:
@@ -1846,7 +1850,7 @@ def initialize_main_module_index_from_generation(app_name: str, generation_hash:
         )
         )
     render_func_name = defined_funcs[-1]
     render_func_name = defined_funcs[-1]
 
 
-    def replace_content(_match):
+    def replace_content(_match: re.Match) -> str:
         return "\n".join(
         return "\n".join(
             [
             [
                 resp.text,
                 resp.text,
@@ -1876,7 +1880,7 @@ def initialize_main_module_index_from_generation(app_name: str, generation_hash:
     main_module_path.write_text(main_module_code)
     main_module_path.write_text(main_module_code)
 
 
 
 
-def format_address_width(address_width) -> int | None:
+def format_address_width(address_width: str | None) -> int | None:
     """Cast address width to an int.
     """Cast address width to an int.
 
 
     Args:
     Args:

+ 23 - 16
reflex/utils/processes.py

@@ -9,18 +9,20 @@ import os
 import signal
 import signal
 import subprocess
 import subprocess
 from concurrent import futures
 from concurrent import futures
+from pathlib import Path
 from typing import Callable, Generator, List, Optional, Tuple, Union
 from typing import Callable, Generator, List, Optional, Tuple, Union
 
 
 import psutil
 import psutil
 import typer
 import typer
 from redis.exceptions import RedisError
 from redis.exceptions import RedisError
+from rich.progress import Progress
 
 
 from reflex import constants
 from reflex import constants
 from reflex.config import environment
 from reflex.config import environment
 from reflex.utils import console, path_ops, prerequisites
 from reflex.utils import console, path_ops, prerequisites
 
 
 
 
-def kill(pid):
+def kill(pid: int):
     """Kill a process.
     """Kill a process.
 
 
     Args:
     Args:
@@ -48,7 +50,7 @@ def get_num_workers() -> int:
     return (os.cpu_count() or 1) * 2 + 1
     return (os.cpu_count() or 1) * 2 + 1
 
 
 
 
-def get_process_on_port(port) -> Optional[psutil.Process]:
+def get_process_on_port(port: int) -> Optional[psutil.Process]:
     """Get the process on the given port.
     """Get the process on the given port.
 
 
     Args:
     Args:
@@ -71,7 +73,7 @@ def get_process_on_port(port) -> Optional[psutil.Process]:
     return None
     return None
 
 
 
 
-def is_process_on_port(port) -> bool:
+def is_process_on_port(port: int) -> bool:
     """Check if a process is running on the given port.
     """Check if a process is running on the given port.
 
 
     Args:
     Args:
@@ -83,7 +85,7 @@ def is_process_on_port(port) -> bool:
     return get_process_on_port(port) is not None
     return get_process_on_port(port) is not None
 
 
 
 
-def kill_process_on_port(port):
+def kill_process_on_port(port: int):
     """Kill the process on the given port.
     """Kill the process on the given port.
 
 
     Args:
     Args:
@@ -94,7 +96,7 @@ def kill_process_on_port(port):
             get_process_on_port(port).kill()  # pyright: ignore [reportOptionalMemberAccess]
             get_process_on_port(port).kill()  # pyright: ignore [reportOptionalMemberAccess]
 
 
 
 
-def change_port(port: str, _type: str) -> str:
+def change_port(port: int, _type: str) -> int:
     """Change the port.
     """Change the port.
 
 
     Args:
     Args:
@@ -105,7 +107,7 @@ def change_port(port: str, _type: str) -> str:
         The new port.
         The new port.
 
 
     """
     """
-    new_port = str(int(port) + 1)
+    new_port = port + 1
     if is_process_on_port(new_port):
     if is_process_on_port(new_port):
         return change_port(new_port, _type)
         return change_port(new_port, _type)
     console.info(
     console.info(
@@ -114,7 +116,7 @@ def change_port(port: str, _type: str) -> str:
     return new_port
     return new_port
 
 
 
 
-def handle_port(service_name: str, port: str, default_port: str) -> str:
+def handle_port(service_name: str, port: int, default_port: int) -> int:
     """Change port if the specified port is in use and is not explicitly specified as a CLI arg or config arg.
     """Change port if the specified port is in use and is not explicitly specified as a CLI arg or config arg.
     otherwise tell the user the port is in use and exit the app.
     otherwise tell the user the port is in use and exit the app.
 
 
@@ -133,7 +135,7 @@ def handle_port(service_name: str, port: str, default_port: str) -> str:
         Exit:when the port is in use.
         Exit:when the port is in use.
     """
     """
     if is_process_on_port(port):
     if is_process_on_port(port):
-        if int(port) == int(default_port):
+        if port == int(default_port):
             return change_port(port, service_name)
             return change_port(port, service_name)
         else:
         else:
             console.error(f"{service_name.capitalize()} port: {port} is already in use")
             console.error(f"{service_name.capitalize()} port: {port} is already in use")
@@ -141,7 +143,12 @@ def handle_port(service_name: str, port: str, default_port: str) -> str:
     return port
     return port
 
 
 
 
-def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
+def new_process(
+    args: str | list[str] | list[str | None] | list[str | Path | None],
+    run: bool = False,
+    show_logs: bool = False,
+    **kwargs,
+):
     """Wrapper over subprocess.Popen to unify the launch of child processes.
     """Wrapper over subprocess.Popen to unify the launch of child processes.
 
 
     Args:
     Args:
@@ -157,7 +164,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
         Exit: When attempting to run a command with a None value.
         Exit: When attempting to run a command with a None value.
     """
     """
     # Check for invalid command first.
     # Check for invalid command first.
-    if None in args:
+    if isinstance(args, list) and None in args:
         console.error(f"Invalid command: {args}")
         console.error(f"Invalid command: {args}")
         raise typer.Exit(1)
         raise typer.Exit(1)
 
 
@@ -191,7 +198,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
     }
     }
     console.debug(f"Running command: {args}")
     console.debug(f"Running command: {args}")
     fn = subprocess.run if run else subprocess.Popen
     fn = subprocess.run if run else subprocess.Popen
-    return fn(args, **kwargs)
+    return fn(args, **kwargs)  # pyright: ignore [reportCallIssue, reportArgumentType]
 
 
 
 
 @contextlib.contextmanager
 @contextlib.contextmanager
@@ -247,7 +254,7 @@ def run_concurrently(*fns: Union[Callable, Tuple]) -> None:
 def stream_logs(
 def stream_logs(
     message: str,
     message: str,
     process: subprocess.Popen,
     process: subprocess.Popen,
-    progress=None,
+    progress: Progress | None = None,
     suppress_errors: bool = False,
     suppress_errors: bool = False,
     analytics_enabled: bool = False,
     analytics_enabled: bool = False,
 ):
 ):
@@ -375,10 +382,10 @@ def get_command_with_loglevel(command: list[str]) -> list[str]:
 
 
 
 
 def run_process_with_fallback(
 def run_process_with_fallback(
-    args,
+    args: list[str],
     *,
     *,
-    show_status_message,
-    fallback=None,
+    show_status_message: str,
+    fallback: str | list | None = None,
     analytics_enabled: bool = False,
     analytics_enabled: bool = False,
     **kwargs,
     **kwargs,
 ):
 ):
@@ -417,7 +424,7 @@ def run_process_with_fallback(
             )
             )
 
 
 
 
-def execute_command_and_return_output(command) -> str | None:
+def execute_command_and_return_output(command: str) -> str | None:
     """Execute a command and return the output.
     """Execute a command and return the output.
 
 
     Args:
     Args:

+ 8 - 6
reflex/utils/pyi_generator.py

@@ -83,7 +83,7 @@ DEFAULT_IMPORTS = {
 }
 }
 
 
 
 
-def _walk_files(path):
+def _walk_files(path: str | Path):
     """Walk all files in a path.
     """Walk all files in a path.
     This can be replaced with Path.walk() in python3.12.
     This can be replaced with Path.walk() in python3.12.
 
 
@@ -114,7 +114,9 @@ def _relative_to_pwd(path: Path) -> Path:
     return path
     return path
 
 
 
 
-def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
+def _get_type_hint(
+    value: Any, type_hint_globals: dict, is_optional: bool = True
+) -> str:
     """Resolve the type hint for value.
     """Resolve the type hint for value.
 
 
     Args:
     Args:
@@ -383,7 +385,7 @@ def _extract_class_props_as_ast_nodes(
     return kwargs
     return kwargs
 
 
 
 
-def type_to_ast(typ, cls: type) -> ast.AST:
+def type_to_ast(typ: Any, cls: type) -> ast.AST:
     """Converts any type annotation into its AST representation.
     """Converts any type annotation into its AST representation.
     Handles nested generic types, unions, etc.
     Handles nested generic types, unions, etc.
 
 
@@ -443,7 +445,7 @@ def type_to_ast(typ, cls: type) -> ast.AST:
     )
     )
 
 
 
 
-def _get_parent_imports(func):
+def _get_parent_imports(func: Callable):
     _imports = {"reflex.vars": ["Var"]}
     _imports = {"reflex.vars": ["Var"]}
     for type_hint in inspect.get_annotations(func).values():
     for type_hint in inspect.get_annotations(func).values():
         try:
         try:
@@ -1052,7 +1054,7 @@ class PyiGenerator:
         pyi_path.write_text(pyi_content)
         pyi_path.write_text(pyi_content)
         logger.info(f"Wrote {relpath}")
         logger.info(f"Wrote {relpath}")
 
 
-    def _get_init_lazy_imports(self, mod, new_tree):
+    def _get_init_lazy_imports(self, mod: tuple | ModuleType, new_tree: ast.AST):
         # retrieve the _SUBMODULES and _SUBMOD_ATTRS from an init file if present.
         # retrieve the _SUBMODULES and _SUBMOD_ATTRS from an init file if present.
         sub_mods = getattr(mod, "_SUBMODULES", None)
         sub_mods = getattr(mod, "_SUBMODULES", None)
         sub_mod_attrs = getattr(mod, "_SUBMOD_ATTRS", None)
         sub_mod_attrs = getattr(mod, "_SUBMOD_ATTRS", None)
@@ -1138,7 +1140,7 @@ class PyiGenerator:
             if pyi_path:
             if pyi_path:
                 self.written_files.append(pyi_path)
                 self.written_files.append(pyi_path)
 
 
-    def scan_all(self, targets, changed_files: list[Path] | None = None):
+    def scan_all(self, targets: list, changed_files: list[Path] | None = None):
         """Scan all targets for class inheriting Component and generate the .pyi files.
         """Scan all targets for class inheriting Component and generate the .pyi files.
 
 
         Args:
         Args:

+ 4 - 4
reflex/utils/registry.py

@@ -22,15 +22,15 @@ def latency(registry: str) -> int:
         return 10_000_000
         return 10_000_000
 
 
 
 
-def average_latency(registry, attempts: int = 3) -> int:
+def average_latency(registry: str, attempts: int = 3) -> int:
     """Get the average latency of a registry.
     """Get the average latency of a registry.
 
 
     Args:
     Args:
-        registry (str): The URL of the registry.
-        attempts (int): The number of attempts to make. Defaults to 10.
+        registry: The URL of the registry.
+        attempts: The number of attempts to make. Defaults to 10.
 
 
     Returns:
     Returns:
-        int: The average latency of the registry in microseconds.
+        The average latency of the registry in microseconds.
     """
     """
     return sum(latency(registry) for _ in range(attempts)) // attempts
     return sum(latency(registry) for _ in range(attempts)) // attempts
 
 

+ 2 - 2
reflex/utils/telemetry.py

@@ -162,7 +162,7 @@ def _send_event(event_data: dict) -> bool:
         return True
         return True
 
 
 
 
-def _send(event, telemetry_enabled, **kwargs):
+def _send(event: str, telemetry_enabled: bool | None, **kwargs):
     from reflex.config import get_config
     from reflex.config import get_config
 
 
     # Get the telemetry_enabled from the config if it is not specified.
     # Get the telemetry_enabled from the config if it is not specified.
@@ -189,7 +189,7 @@ def send(event: str, telemetry_enabled: bool | None = None, **kwargs):
         kwargs: Additional data to send with the event.
         kwargs: Additional data to send with the event.
     """
     """
 
 
-    async def async_send(event, telemetry_enabled, **kwargs):
+    async def async_send(event: str, telemetry_enabled: bool | None, **kwargs):
         return _send(event, telemetry_enabled, **kwargs)
         return _send(event, telemetry_enabled, **kwargs)
 
 
     try:
     try:

+ 4 - 4
reflex/utils/types.py

@@ -157,7 +157,7 @@ class Unset:
 
 
 
 
 @lru_cache()
 @lru_cache()
-def get_origin(tp):
+def get_origin(tp: Any):
     """Get the origin of a class.
     """Get the origin of a class.
 
 
     Args:
     Args:
@@ -240,7 +240,7 @@ def is_literal(cls: GenericType) -> bool:
     return get_origin(cls) is Literal
     return get_origin(cls) is Literal
 
 
 
 
-def has_args(cls) -> bool:
+def has_args(cls: Type) -> bool:
     """Check if the class has generic parameters.
     """Check if the class has generic parameters.
 
 
     Args:
     Args:
@@ -753,7 +753,7 @@ def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
     return type_ in allowed_types
     return type_ in allowed_types
 
 
 
 
-def is_encoded_fstring(value) -> bool:
+def is_encoded_fstring(value: Any) -> bool:
     """Check if a value is an encoded Var f-string.
     """Check if a value is an encoded Var f-string.
 
 
     Args:
     Args:
@@ -796,7 +796,7 @@ def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
             )
             )
 
 
 
 
-def validate_parameter_literals(func):
+def validate_parameter_literals(func: Callable):
     """Decorator to check that the arguments passed to a function
     """Decorator to check that the arguments passed to a function
     correspond to the correct function parameter if it (the parameter)
     correspond to the correct function parameter if it (the parameter)
     is a literal type.
     is a literal type.

+ 36 - 20
reflex/vars/base.py

@@ -493,20 +493,30 @@ class Var(Generic[VAR_TYPE]):
 
 
     @overload
     @overload
     def _replace(
     def _replace(
-        self, _var_type: Type[OTHER_VAR_TYPE], merge_var_data=None, **kwargs: Any
+        self,
+        _var_type: Type[OTHER_VAR_TYPE],
+        merge_var_data: VarData | None = None,
+        **kwargs: Any,
     ) -> Var[OTHER_VAR_TYPE]: ...
     ) -> Var[OTHER_VAR_TYPE]: ...
 
 
     @overload
     @overload
     def _replace(
     def _replace(
-        self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
+        self,
+        _var_type: GenericType | None = None,
+        merge_var_data: VarData | None = None,
+        **kwargs: Any,
     ) -> Self: ...
     ) -> Self: ...
 
 
     def _replace(
     def _replace(
-        self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
+        self,
+        _var_type: GenericType | None = None,
+        merge_var_data: VarData | None = None,
+        **kwargs: Any,
     ) -> Self | Var:
     ) -> Self | Var:
         """Make a copy of this Var with updated fields.
         """Make a copy of this Var with updated fields.
 
 
         Args:
         Args:
+            _var_type: The new type of the Var.
             merge_var_data: VarData to merge into the existing VarData.
             merge_var_data: VarData to merge into the existing VarData.
             **kwargs: Var fields to update.
             **kwargs: Var fields to update.
 
 
@@ -1308,7 +1318,7 @@ class LiteralVar(Var):
         _var_literal_subclasses.append((cls, var_subclass))
         _var_literal_subclasses.append((cls, var_subclass))
 
 
     @classmethod
     @classmethod
-    def create(
+    def create(  # pyright: ignore [reportArgumentType]
         cls,
         cls,
         value: Any,
         value: Any,
         _var_data: VarData | None = None,
         _var_data: VarData | None = None,
@@ -1556,7 +1566,7 @@ def figure_out_type(value: Any) -> types.GenericType:
 class cached_property_no_lock(functools.cached_property):  # noqa: N801
 class cached_property_no_lock(functools.cached_property):  # noqa: N801
     """A special version of functools.cached_property that does not use a lock."""
     """A special version of functools.cached_property that does not use a lock."""
 
 
-    def __init__(self, func):
+    def __init__(self, func: Callable):
         """Initialize the cached_property_no_lock.
         """Initialize the cached_property_no_lock.
 
 
         Args:
         Args:
@@ -1729,7 +1739,7 @@ class CallableVar(Var):
         object.__setattr__(self, "fn", fn)
         object.__setattr__(self, "fn", fn)
         object.__setattr__(self, "original_var", original_var)
         object.__setattr__(self, "original_var", original_var)
 
 
-    def __call__(self, *args, **kwargs) -> Var:
+    def __call__(self, *args: Any, **kwargs: Any) -> Var:
         """Call the decorated function.
         """Call the decorated function.
 
 
         Args:
         Args:
@@ -1885,10 +1895,16 @@ class ComputedVar(Var[RETURN_TYPE]):
         object.__setattr__(self, "_fget", fget)
         object.__setattr__(self, "_fget", fget)
 
 
     @override
     @override
-    def _replace(self, merge_var_data=None, **kwargs: Any) -> Self:
+    def _replace(
+        self,
+        _var_type: Any = None,
+        merge_var_data: VarData | None = None,
+        **kwargs: Any,
+    ) -> Self:
         """Replace the attributes of the ComputedVar.
         """Replace the attributes of the ComputedVar.
 
 
         Args:
         Args:
+            _var_type: ignored in ComputedVar.
             merge_var_data: VarData to merge into the existing VarData.
             merge_var_data: VarData to merge into the existing VarData.
             **kwargs: Var fields to update.
             **kwargs: Var fields to update.
 
 
@@ -2002,7 +2018,7 @@ class ComputedVar(Var[RETURN_TYPE]):
     @overload
     @overload
     def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ...
     def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ...
 
 
-    def __get__(self, instance: BaseState | None, owner):
+    def __get__(self, instance: BaseState | None, owner: Type):
         """Get the ComputedVar value.
         """Get the ComputedVar value.
 
 
         If the value is already cached on the instance, return the cached value.
         If the value is already cached on the instance, return the cached value.
@@ -2165,7 +2181,7 @@ class ComputedVar(Var[RETURN_TYPE]):
             self_is_top_of_stack = False
             self_is_top_of_stack = False
         return d
         return d
 
 
-    def mark_dirty(self, instance) -> None:
+    def mark_dirty(self, instance: BaseState) -> None:
         """Mark this ComputedVar as dirty.
         """Mark this ComputedVar as dirty.
 
 
         Args:
         Args:
@@ -2887,7 +2903,7 @@ MAPPING_TYPE = TypeVar("MAPPING_TYPE", bound=Mapping)
 class Field(Generic[FIELD_TYPE]):
 class Field(Generic[FIELD_TYPE]):
     """Shadow class for Var to allow for type hinting in the IDE."""
     """Shadow class for Var to allow for type hinting in the IDE."""
 
 
-    def __set__(self, instance, value: FIELD_TYPE):
+    def __set__(self, instance: Any, value: FIELD_TYPE):
         """Set the Var.
         """Set the Var.
 
 
         Args:
         Args:
@@ -2896,43 +2912,43 @@ class Field(Generic[FIELD_TYPE]):
         """
         """
 
 
     @overload
     @overload
-    def __get__(self: Field[bool], instance: None, owner) -> BooleanVar: ...
+    def __get__(self: Field[bool], instance: None, owner: Any) -> BooleanVar: ...
 
 
     @overload
     @overload
     def __get__(
     def __get__(
-        self: Field[int] | Field[float] | Field[int | float], instance: None, owner
+        self: Field[int] | Field[float] | Field[int | float], instance: None, owner: Any
     ) -> NumberVar: ...
     ) -> NumberVar: ...
 
 
     @overload
     @overload
-    def __get__(self: Field[str], instance: None, owner) -> StringVar: ...
+    def __get__(self: Field[str], instance: None, owner: Any) -> StringVar: ...
 
 
     @overload
     @overload
-    def __get__(self: Field[None], instance: None, owner) -> NoneVar: ...
+    def __get__(self: Field[None], instance: None, owner: Any) -> NoneVar: ...
 
 
     @overload
     @overload
     def __get__(
     def __get__(
         self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]],
         self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]],
         instance: None,
         instance: None,
-        owner,
+        owner: Any,
     ) -> ArrayVar[List[V]]: ...
     ) -> ArrayVar[List[V]]: ...
 
 
     @overload
     @overload
     def __get__(
     def __get__(
-        self: Field[MAPPING_TYPE], instance: None, owner
+        self: Field[MAPPING_TYPE], instance: None, owner: Any
     ) -> ObjectVar[MAPPING_TYPE]: ...
     ) -> ObjectVar[MAPPING_TYPE]: ...
 
 
     @overload
     @overload
     def __get__(
     def __get__(
-        self: Field[BASE_TYPE], instance: None, owner
+        self: Field[BASE_TYPE], instance: None, owner: Any
     ) -> ObjectVar[BASE_TYPE]: ...
     ) -> ObjectVar[BASE_TYPE]: ...
 
 
     @overload
     @overload
-    def __get__(self, instance: None, owner) -> Var[FIELD_TYPE]: ...
+    def __get__(self, instance: None, owner: Any) -> Var[FIELD_TYPE]: ...
 
 
     @overload
     @overload
-    def __get__(self, instance, owner) -> FIELD_TYPE: ...
+    def __get__(self, instance: Any, owner: Any) -> FIELD_TYPE: ...
 
 
-    def __get__(self, instance, owner):  # pyright: ignore [reportInconsistentOverload]
+    def __get__(self, instance: Any, owner: Any):  # pyright: ignore [reportInconsistentOverload]
         """Get the Var.
         """Get the Var.
 
 
         Args:
         Args:

+ 4 - 0
reflex/vars/function.py

@@ -210,6 +210,7 @@ class FunctionStringVar(FunctionVar[CALLABLE_TYPE]):
 
 
         Args:
         Args:
             func: The function to call.
             func: The function to call.
+            _var_type: The type of the Var.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:
@@ -268,6 +269,7 @@ class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]):
         Args:
         Args:
             func: The function to call.
             func: The function to call.
             *args: The arguments to call the function with.
             *args: The arguments to call the function with.
+            _var_type: The type of the Var.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:
@@ -385,6 +387,7 @@ class ArgsFunctionOperation(CachedVarOperation, FunctionVar):
             return_expr: The return expression of the function.
             return_expr: The return expression of the function.
             rest: The name of the rest argument.
             rest: The name of the rest argument.
             explicit_return: Whether to use explicit return syntax.
             explicit_return: Whether to use explicit return syntax.
+            _var_type: The type of the Var.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:
@@ -441,6 +444,7 @@ class ArgsFunctionOperationBuilder(CachedVarOperation, BuilderFunctionVar):
             return_expr: The return expression of the function.
             return_expr: The return expression of the function.
             rest: The name of the rest argument.
             rest: The name of the rest argument.
             explicit_return: Whether to use explicit return syntax.
             explicit_return: Whether to use explicit return syntax.
+            _var_type: The type of the Var.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:

+ 1 - 1
reflex/vars/object.py

@@ -253,7 +253,7 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=Mapping):
         name: str,
         name: str,
     ) -> ObjectItemOperation: ...
     ) -> ObjectItemOperation: ...
 
 
-    def __getattr__(self, name) -> Var:
+    def __getattr__(self, name: str) -> Var:
         """Get an attribute of the var.
         """Get an attribute of the var.
 
 
         Args:
         Args:

+ 6 - 3
reflex/vars/sequence.py

@@ -780,7 +780,7 @@ class ConcatVarOperation(CachedVarOperation, StringVar[str]):
         """Create a var from a string value.
         """Create a var from a string value.
 
 
         Args:
         Args:
-            value: The values to concatenate.
+            *value: The values to concatenate.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:
@@ -1323,6 +1323,7 @@ class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]):
 
 
         Args:
         Args:
             value: The value to create the var from.
             value: The value to create the var from.
+            _var_type: The type of the var.
             _var_data: Additional hooks and imports associated with the Var.
             _var_data: Additional hooks and imports associated with the Var.
 
 
         Returns:
         Returns:
@@ -1618,7 +1619,9 @@ def array_contains_field_operation(
 
 
 
 
 @var_operation
 @var_operation
-def array_contains_operation(haystack: ArrayVar, needle: Any | Var):
+def array_contains_operation(
+    haystack: ArrayVar, needle: Any | Var
+) -> CustomVarOperationReturn[bool]:
     """Check if an array contains an element.
     """Check if an array contains an element.
 
 
     Args:
     Args:
@@ -1661,7 +1664,7 @@ if TYPE_CHECKING:
 def map_array_operation(
 def map_array_operation(
     array: ArrayVar[ARRAY_VAR_TYPE],
     array: ArrayVar[ARRAY_VAR_TYPE],
     function: FunctionVar,
     function: FunctionVar,
-):
+) -> CustomVarOperationReturn[List[Any]]:
     """Map a function over an array.
     """Map a function over an array.
 
 
     Args:
     Args:

+ 2 - 2
scripts/wait_for_listening_port.py

@@ -14,7 +14,7 @@ from typing import Tuple
 import psutil
 import psutil
 
 
 
 
-def _pid_exists(pid):
+def _pid_exists(pid: int):
     # os.kill(pid, 0) doesn't work on Windows (actually kills the PID)
     # os.kill(pid, 0) doesn't work on Windows (actually kills the PID)
     # psutil.pid_exists() doesn't work on Windows (does os.kill underneath)
     # psutil.pid_exists() doesn't work on Windows (does os.kill underneath)
     # psutil.pids() seems to return the right thing. Inefficient but doesn't matter - keeps things simple.
     # psutil.pids() seems to return the right thing. Inefficient but doesn't matter - keeps things simple.
@@ -23,7 +23,7 @@ def _pid_exists(pid):
     return pid in psutil.pids()
     return pid in psutil.pids()
 
 
 
 
-def _wait_for_port(port, server_pid, timeout) -> Tuple[bool, str]:
+def _wait_for_port(port: int, server_pid: int, timeout: float) -> Tuple[bool, str]:
     start = time.time()
     start = time.time()
     print(f"Waiting for up to {timeout} seconds for port {port} to start listening.")  # noqa: T201
     print(f"Waiting for up to {timeout} seconds for port {port} to start listening.")  # noqa: T201
     while True:
     while True: