diff --git a/.github/workflows/check_outdated_dependencies.yml b/.github/workflows/check_outdated_dependencies.yml index 74524e56d43..4d77d96dbd2 100644 --- a/.github/workflows/check_outdated_dependencies.yml +++ b/.github/workflows/check_outdated_dependencies.yml @@ -30,14 +30,14 @@ jobs: echo "Outdated:" echo "$outdated" - filtered_outdated=$(echo "$outdated" | grep -vE 'pyright|ruff' || true) + filtered_outdated=$(echo "$outdated" | grep -vE 'ty|ruff' || true) if [ ! -z "$filtered_outdated" ]; then echo "Outdated dependencies found:" echo "$filtered_outdated" exit 1 else - echo "All dependencies are up to date. (pyright and ruff are ignored)" + echo "All dependencies are up to date. (ty and ruff are ignored)" fi frontend: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c4bb23170c4..6a45cd9193f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,11 +34,12 @@ repos: require_serial: true - repo: local hooks: - - id: pyright - name: pyright - entry: uv run --no-sync pyright + - id: ty + name: ty + entry: ty check language: system types: [python] + pass_filenames: false require_serial: true - repo: https://github.com/biomejs/pre-commit rev: 19865851e014cbe6138e295365f95ca51bf953f8 # v0.6.1 diff --git a/AGENTS.md b/AGENTS.md index e2a4e287b03..2fd6826e8c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ uv run pytest tests/units --cov --no-cov-on-fail --cov-report= # unit tests (> uv run pytest tests/integration # integration tests (slow) uv run ruff check . # lint uv run ruff format . # format -uv run pyright reflex tests # type check +uv run ty check # type check uv run python scripts/make_pyi.py # regenerate .pyi stubs uv run pre-commit run --all-files # all pre-commit hooks ``` @@ -122,7 +122,7 @@ if TYPE_CHECKING: Before submitting: 1. Tests pass with adequate coverage 2. `uv run ruff check .` and `uv run ruff format .` clean -3. `uv run pyright reflex tests` passes +3. `uv run ty check` passes 4. `pyi_hashes.json` updated if components changed 5. Documentation updated if user-facing behavior changed 6. Deprecation warnings added if breaking changes introduced diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 823202f3cbd..c956e181f14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,7 +73,7 @@ Next make sure all the following tests pass. This ensures that every new change ```bash uv run ruff check . -uv run pyright reflex tests +uv run ty check ``` Finally, run `ruff` to format your code. @@ -82,7 +82,7 @@ Finally, run `ruff` to format your code. uv run ruff format . ``` -Consider installing git pre-commit hooks so Ruff, Pyright, and `make_pyi` will run automatically before each commit. +Consider installing git pre-commit hooks so Ruff, ty, and `make_pyi` will run automatically before each commit. ```bash uv run pre-commit install diff --git a/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index a7a2285d71a..1bfda6a815a 100644 --- a/packages/reflex-base/src/reflex_base/components/component.py +++ b/packages/reflex-base/src/reflex_base/components/component.py @@ -2,6 +2,7 @@ from __future__ import annotations +import builtins import contextlib import dataclasses import enum @@ -112,7 +113,7 @@ def field( default_factory: Callable[[], FIELD_TYPE] | None = None, is_javascript_property: bool | None = None, doc: str | None = None, -) -> FIELD_TYPE: +) -> Any: """Create a field for a component. Args: @@ -130,7 +131,7 @@ def field( if default is not MISSING and default_factory is not None: msg = "cannot specify both default and default_factory" raise ValueError(msg) - return ComponentField( # pyright: ignore [reportReturnType] + return ComponentField( default=default, default_factory=default_factory, is_javascript=is_javascript_property, @@ -362,7 +363,7 @@ def __copy__(self) -> BaseComponent: def _clear_compile_caches(self) -> None: """Clear cached render/compiler artifacts after compile-time mutation.""" - attrs = cast("dict[str, Any]", vars(self)) + attrs = vars(self) for attr in ( "_cached_render_result", "_vars_cache", @@ -437,7 +438,7 @@ def _get_all_imports(self) -> ParsedImportDict: """ @abstractmethod - def _get_all_dynamic_imports(self) -> set[str]: + def _get_all_dynamic_imports(self) -> builtins.set[str]: """Get dynamic imports for the component. Returns: @@ -464,7 +465,7 @@ def _get_all_refs(self) -> dict[str, None]: class ComponentNamespace(SimpleNamespace): """A namespace to manage components with subcomponents.""" - def __hash__(self) -> int: # pyright: ignore [reportIncompatibleVariableOverride] + def __hash__(self) -> int: """Get the hash of the namespace. Returns: @@ -650,15 +651,15 @@ class TriggerDefinition: description="Fired when focus has left the element (or left some element inside of it). For example, it is called when the user clicks outside of a focused text input.", ), EventTriggers.ON_CLICK: TriggerDefinition( - spec=pointer_event_spec, # pyright: ignore [reportArgumentType] + spec=pointer_event_spec, description="Fired when the user clicks on an element. For example, it's called when the user clicks on a button.", ), EventTriggers.ON_CONTEXT_MENU: TriggerDefinition( - spec=pointer_event_spec, # pyright: ignore [reportArgumentType] + spec=pointer_event_spec, description="Fired when the user right-clicks on an element.", ), EventTriggers.ON_DOUBLE_CLICK: TriggerDefinition( - spec=pointer_event_spec, # pyright: ignore [reportArgumentType] + spec=pointer_event_spec, description="Fired when the user double-clicks on an element.", ), EventTriggers.ON_MOUSE_DOWN: TriggerDefinition( @@ -1081,7 +1082,7 @@ def get_event_triggers(cls) -> dict[str, types.ArgsSpec | Sequence[types.ArgsSpe """ # Look for component specific triggers, # e.g. variable declared as EventHandler types. - return DEFAULT_TRIGGERS | args_specs_from_fields(cls.get_fields()) # pyright: ignore [reportOperatorIssue] + return DEFAULT_TRIGGERS | args_specs_from_fields(cls.get_fields()) def __repr__(self) -> str: """Represent the component in React. @@ -1325,9 +1326,11 @@ def _get_component_style(self, styles: ComponentStyle | Style) -> Style | None: The style of the component. """ component_style = None - if (style := styles.get(type(self))) is not None: # pyright: ignore [reportArgumentType] + if isinstance(styles, Style): + return component_style + if (style := styles.get(type(self))) is not None: component_style = Style(style) - if (style := styles.get(self.create)) is not None: # pyright: ignore [reportArgumentType] + if (style := styles.get(self.create)) is not None: component_style = Style(style) return component_style @@ -2250,13 +2253,13 @@ def get_args_spec(key: str) -> types.ArgsSpec | Sequence[types.ArgsSpec]: to_camel_cased_props = { format.to_camel_case(key): None for key in props if key not in event_types } - self.get_props = lambda: to_camel_cased_props # pyright: ignore [reportIncompatibleVariableOverride] + self.get_props = lambda: to_camel_cased_props # ty:ignore[invalid-assignment] # Unset the style. self.style = Style() # Set the tag to the name of the function. - self.tag = format.to_title_case(self.component_fn.__name__) + self.tag = format.to_title_case(format.callable_name(self.component_fn)) for key, value in props.items(): # Skip kwargs that are not props. @@ -2330,7 +2333,7 @@ def fn(*args): else event.args_spec[0] ) names = inspect.getfullargspec(arg_spec).args - fn.__signature__ = inspect.Signature( # pyright: ignore[reportFunctionMemberAccess] + fn.__signature__ = inspect.Signature( # ty:ignore[unresolved-attribute] parameters=[ inspect.Parameter( name=name, @@ -2607,7 +2610,7 @@ def _format_patterns_into_condition(patterns: list, element: Var) -> Var: ) -def render_dict_to_var(tag: dict | Component | str) -> Var: +def render_dict_to_var(tag: dict[str, Any] | Component | str) -> Var: """Convert a render dict to a Var. Args: @@ -2616,37 +2619,38 @@ def render_dict_to_var(tag: dict | Component | str) -> Var: Returns: The Var. """ + if isinstance(tag, Component): + return render_dict_to_var(tag.render()) if not isinstance(tag, dict): - if isinstance(tag, Component): - return render_dict_to_var(tag.render()) return Var.create(tag) + render_dict: dict[str, Any] = tag - if "contents" in tag: - return Var(tag["contents"]) + if "contents" in render_dict: + return Var(render_dict["contents"]) - if "iterable" in tag: + if "iterable" in render_dict: function_return = LiteralArrayVar.create([ - render_dict_to_var(child.render()) for child in tag["children"] + render_dict_to_var(child.render()) for child in render_dict["children"] ]) func = ArgsFunctionOperation.create( - (tag["arg_var_name"], tag["index_var_name"]), + (render_dict["arg_var_name"], render_dict["index_var_name"]), function_return, ) return FunctionStringVar.create("Array.prototype.map.call").call( - tag["iterable"] - if not isinstance(tag["iterable"], ObjectVar) - else tag["iterable"].items(), + render_dict["iterable"] + if not isinstance(render_dict["iterable"], ObjectVar) + else render_dict["iterable"].items(), func, ) - if "match_cases" in tag: - element = Var(tag["cond"]) + if "match_cases" in render_dict: + element = Var(render_dict["cond"]) - conditionals = render_dict_to_var(tag["default"]) + conditionals = render_dict_to_var(render_dict["default"]) - for case in tag["match_cases"][::-1]: + for case in render_dict["match_cases"][::-1]: patterns, return_value = case condition = _format_patterns_into_condition(patterns, element) @@ -2658,18 +2662,18 @@ def render_dict_to_var(tag: dict | Component | str) -> Var: return conditionals - if "cond_state" in tag: + if "cond_state" in render_dict: return ternary_operation( - Var(tag["cond_state"]), - render_dict_to_var(tag["true_value"]), - render_dict_to_var(tag["false_value"]) - if tag["false_value"] is not None + Var(render_dict["cond_state"]), + render_dict_to_var(render_dict["true_value"]), + render_dict_to_var(render_dict["false_value"]) + if render_dict["false_value"] is not None else LiteralNoneVar.create(), ) - props = Var("({" + ",".join(tag["props"]) + "})") + props = Var("({" + ",".join(render_dict["props"]) + "})") - raw_tag_name = tag.get("name") + raw_tag_name = render_dict.get("name") tag_name = Var(raw_tag_name or "Fragment") return FunctionStringVar.create( @@ -2677,7 +2681,7 @@ def render_dict_to_var(tag: dict | Component | str) -> Var: ).call( tag_name, props, - *[render_dict_to_var(child) for child in tag["children"]], + *[render_dict_to_var(child) for child in render_dict["children"]], ) diff --git a/packages/reflex-base/src/reflex_base/components/field.py b/packages/reflex-base/src/reflex_base/components/field.py index 5487bdd923d..f1c9a09ed30 100644 --- a/packages/reflex-base/src/reflex_base/components/field.py +++ b/packages/reflex-base/src/reflex_base/components/field.py @@ -35,7 +35,7 @@ def __init__( # Process type annotation type_origin = get_origin(annotated_type) or annotated_type if type_origin is Annotated: - type_origin = annotated_type.__origin__ # pyright: ignore [reportAttributeAccessIssue] + type_origin = annotated_type.__origin__ # ty:ignore[unresolved-attribute] # For Annotated types, use the actual type inside the annotation self.type_ = annotated_type else: diff --git a/packages/reflex-base/src/reflex_base/components/props.py b/packages/reflex-base/src/reflex_base/components/props.py index 13f1eabca59..96371d90fbf 100644 --- a/packages/reflex-base/src/reflex_base/components/props.py +++ b/packages/reflex-base/src/reflex_base/components/props.py @@ -2,6 +2,7 @@ from __future__ import annotations +import builtins from collections.abc import Callable from dataclasses import _MISSING_TYPE, MISSING from typing import Any, TypeVar, get_args, get_origin @@ -158,11 +159,11 @@ def props_field( if default is not MISSING and default_factory is not None: msg = "cannot specify both default and default_factory" raise ValueError(msg) - return PropsField( # pyright: ignore [reportReturnType] + return PropsField( default=default, default_factory=default_factory, annotated_type=MISSING, - ) + ) # ty:ignore[invalid-return-type] @dataclass_transform(field_specifiers=(props_field,)) @@ -283,7 +284,7 @@ def __init__(self, **kwargs): ) @classmethod - def get_fields(cls) -> dict[str, Any]: + def get_fields(cls) -> builtins.dict[str, Any]: """Get the fields of the object. Returns: diff --git a/packages/reflex-base/src/reflex_base/environment.py b/packages/reflex-base/src/reflex_base/environment.py index 956cd00d6cd..7370b626957 100644 --- a/packages/reflex-base/src/reflex_base/environment.py +++ b/packages/reflex-base/src/reflex_base/environment.py @@ -451,7 +451,7 @@ def get_type_hints_environment(cls: type) -> dict[str, Any]: return get_type_hints(cls) -class env_var: # noqa: N801 # pyright: ignore [reportRedeclaration] +class env_var: # noqa: N801 """Descriptor for environment variables.""" name: str @@ -713,7 +713,7 @@ class EnvironmentVariables: try: from dotenv import load_dotenv except ImportError: - load_dotenv = None + load_dotenv = None # ty:ignore[invalid-assignment] def _paths_from_env_files(env_files: str) -> list[Path]: diff --git a/packages/reflex-base/src/reflex_base/event/__init__.py b/packages/reflex-base/src/reflex_base/event/__init__.py index 97a8af96ba1..06b97e2bb8b 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -13,6 +13,7 @@ TYPE_CHECKING, Annotated, Any, + ClassVar, Generic, Literal, NoReturn, @@ -118,7 +119,7 @@ def from_event_type( for e in events: if callable(e) and getattr(e, "__name__", "") == "": # A lambda was returned, assume the user wants to call it with no args. - e = e() + e = e() # ty:ignore[call-top-callable] if isinstance(e, Event): # If the event is already an event, append it to the list. if router_data is not None and e.router_data != router_data: @@ -406,7 +407,7 @@ def _parameters(self) -> Mapping[str, inspect.Parameter]: return parameters @classmethod - def __class_getitem__(cls, args_spec: str) -> Annotated: + def __class_getitem__(cls, args_spec: str) -> Annotated: # ty:ignore[invalid-type-form] """Get a typed EventHandler. Args: @@ -415,7 +416,7 @@ def __class_getitem__(cls, args_spec: str) -> Annotated: Returns: The EventHandler class item. """ - return Annotated[cls, args_spec] + return Annotated[cls, args_spec] # ty:ignore[invalid-type-form] @property def is_background(self) -> bool: @@ -512,7 +513,7 @@ class EventSpec(EventActionsMixin): args: The arguments to pass to the function. """ - handler: EventHandler = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] + handler: EventHandler = dataclasses.field(default=None) # ty:ignore[invalid-assignment] client_handler_name: str = dataclasses.field(default="") @@ -724,7 +725,7 @@ def create( events.append(v) elif isinstance(v, FunctionVar): # Apply the args_spec transformations as partial arguments to the function. - events.append(v.partial(*parse_args_spec(args_spec)[0])) + events.append(v.partial(*parse_args_spec(args_spec)[0])) # ty:ignore[no-matching-overload] elif isinstance(v, Callable): # Call the lambda to get the event chain. events.extend(call_event_fn(v, args_spec, key=key)) @@ -989,7 +990,7 @@ def __call__(self, *values: Var[T]) -> tuple[Var[T], ...]: @overload -def passthrough_event_spec( # pyright: ignore [reportOverlappingOverload] +def passthrough_event_spec( event_type: type[T], / ) -> Callable[[Var[T]], tuple[Var[T]]]: ... @@ -1000,11 +1001,25 @@ def passthrough_event_spec( ) -> Callable[[Var[T], Var[U]], tuple[Var[T], Var[U]]]: ... +@overload +def passthrough_event_spec( + event_type: types.UnionType, / +) -> Callable[[Var[Any]], tuple[Var[Any]]]: ... + + +@overload +def passthrough_event_spec( + event_type_1: types.UnionType | type[T], + event_type2: types.UnionType | type[U], + /, +) -> Callable[[Var[Any], Var[Any]], tuple[Var[Any], Var[Any]]]: ... + + @overload def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: ... -def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: # pyright: ignore [reportInconsistentOverload] +def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: """A helper function that returns the input event as output. Args: @@ -1017,22 +1032,22 @@ def passthrough_event_spec(*event_types: type[T]) -> IdentityEventReturn[T]: # def inner(*values: Var[T]) -> tuple[Var[T], ...]: return values - inner_type = tuple(Var[event_type] for event_type in event_types) - return_annotation = tuple[inner_type] + inner_type = tuple(Var[event_type] for event_type in event_types) # ty:ignore[invalid-type-form] + return_annotation = tuple[inner_type] # ty:ignore[invalid-type-form] - inner.__signature__ = inspect.signature(inner).replace( # pyright: ignore [reportFunctionMemberAccess] + inner.__signature__ = inspect.signature(inner).replace( # ty:ignore[unresolved-attribute] parameters=[ inspect.Parameter( f"ev_{i}", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, - annotation=Var[event_type], + annotation=Var[event_type], # ty:ignore[invalid-type-form] ) for i, event_type in enumerate(event_types) ], return_annotation=return_annotation, ) for i, event_type in enumerate(event_types): - inner.__annotations__[f"ev_{i}"] = Var[event_type] + inner.__annotations__[f"ev_{i}"] = Var[event_type] # ty:ignore[invalid-type-form] inner.__annotations__["return"] = return_annotation return inner @@ -1228,7 +1243,7 @@ def fn(): return None fn.__qualname__ = name - fn.__signature__ = sig # pyright: ignore [reportFunctionMemberAccess] + fn.__signature__ = sig # ty:ignore[unresolved-attribute] return EventSpec( handler=EventHandler(fn=fn), args=tuple( @@ -1947,7 +1962,7 @@ def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]): # if there's multiple, the first is the default if isinstance(arg_spec, Sequence): annotations = [get_type_hints(one_arg_spec) for one_arg_spec in arg_spec] - arg_spec = arg_spec[0] + arg_spec = arg_spec[0] # ty:ignore[invalid-assignment] else: annotations = [get_type_hints(arg_spec)] @@ -1957,11 +1972,11 @@ def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]): arg_spec(*[ Var(f"_{l_arg}").to( unwrap_var_annotation( - resolve_annotation(annotations[0], l_arg, spec=arg_spec) + resolve_annotation(annotations[0], l_arg, spec=arg_spec) # ty:ignore[invalid-argument-type] ) ) for l_arg in spec.args - ]) + ]) # ty:ignore[call-non-callable] ), annotations @@ -2225,7 +2240,7 @@ def fix_events( for e in events: if callable(e) and getattr(e, "__name__", "") == "": # A lambda was returned, assume the user wants to call it with no args. - e = e() + e = e() # ty:ignore[call-top-callable] if isinstance(e, Event): # If the event is already an event, append it to the list. out.append(e) @@ -2285,7 +2300,7 @@ def bool(self) -> NoReturn: class LiteralEventVar(VarOperationCall, LiteralVar, EventVar): """A literal event var.""" - _var_value: EventSpec = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] + _var_value: EventSpec = dataclasses.field(default=None) # ty:ignore[invalid-assignment] def __hash__(self) -> int: """Get the hash of the var. @@ -2321,7 +2336,7 @@ def no_args(): try: value = call_event_handler(value, no_args) except EventFnArgMismatchError: - msg = f"Event handler {value.fn.__qualname__} used inside of a rx.cond() must not take any arguments." + msg = f"Event handler {value.fn.__qualname__} used inside of a rx.cond() must not take any arguments." # ty:ignore[unresolved-attribute] raise EventFnArgMismatchError(msg) from None return cls( @@ -2372,7 +2387,7 @@ def bool(self) -> NoReturn: class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainVar): """A literal event chain var.""" - _var_value: EventChain = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] + _var_value: EventChain = dataclasses.field(default=None) # ty:ignore[invalid-assignment] def __hash__(self) -> int: """Get the hash of the var. @@ -2405,7 +2420,7 @@ def create( if isinstance(value.args_spec, Sequence) else value.args_spec ) - sig = inspect.signature(arg_spec) # pyright: ignore [reportArgumentType] + sig = inspect.signature(arg_spec) # ty:ignore[invalid-argument-type] arg_vars = () if sig.parameters: arg_def = tuple(f"_{p}" for p in sig.parameters) @@ -2442,7 +2457,7 @@ def create( LiteralVar.create([LiteralVar.create(event)]), arg_def_expr, _EMPTY_EVENT_ACTIONS, - ) + ) # ty:ignore[no-matching-overload] ) for event in value.events ] @@ -2453,7 +2468,7 @@ def create( _EMPTY_EVENTS, arg_def_expr, _EMPTY_EVENT_ACTIONS, - ) + ) # ty:ignore[no-matching-overload] ) if len(statements) == 1 and not value.event_actions: @@ -2506,7 +2521,7 @@ def __init__(self, func: Callable[[Any, Unpack[P]], Any]): Args: func: The function to be wrapped. """ - self.func = func + self.func = func # ty:ignore[invalid-assignment] @overload def __call__( @@ -2542,7 +2557,7 @@ def __call__( value4: V4 | Var[V4], ) -> "EventCallback[Unpack[Q]]": ... - def __call__(self, *values) -> "EventCallback": # pyright: ignore [reportInconsistentOverload] + def __call__(self, *values) -> "EventCallback": """Call the function with the values. Args: @@ -2551,7 +2566,7 @@ def __call__(self, *values) -> "EventCallback": # pyright: ignore [reportIncons Returns: The function with the values. """ - return self.func(*values) # pyright: ignore [reportArgumentType] + return self.func(*values) @overload def __get__( @@ -2559,7 +2574,7 @@ def __get__( ) -> "EventCallback[Unpack[P]]": ... @overload - def __get__(self, instance: Any, owner: Any) -> "Callable[[Unpack[P]]]": ... + def __get__(self, instance: Any, owner: Any) -> "Callable[[Unpack[P]], Any]": ... def __get__(self, instance: Any, owner: Any) -> Callable: """Get the function with the instance bound to it. @@ -2649,6 +2664,12 @@ def __call__(self, *args: Var) -> Any: class EventNamespace: """A namespace for event related classes.""" + if TYPE_CHECKING: + event: ClassVar["type[EventNamespace]"] + __path__: ClassVar[Any] + __spec__: ClassVar[Any] + __package__: ClassVar[str | None] + # Core Event Classes Event = Event EventActionsMixin = EventActionsMixin @@ -2819,7 +2840,7 @@ def wrapper( types = get_type_hints(func) state_arg_name = next(iter(inspect.signature(func).parameters), None) state_cls = state_arg_name and types.get(state_arg_name) - if state_cls and issubclass(state_cls, BaseState): + if state_cls and issubclass(state_cls, BaseState): # ty:ignore[invalid-argument-type] name = ( (func.__module__ + "." + qualname) .replace(".", "_") @@ -2845,7 +2866,7 @@ def wrapper( event_actions = _build_event_actions() if event_actions: setattr(func, EVENT_ACTIONS_MARKER, event_actions) - return func # pyright: ignore [reportReturnType] + return func if func is not None: return wrapper(func) @@ -2899,7 +2920,7 @@ def wrapper( __file__ = __file__ @property - def BaseState(self) -> "type[BaseState]": # noqa: N802 + def BaseState(self) -> "type[BaseState]": # noqa: N802 # ty:ignore[invalid-type-form] """Get the BaseState class. A reference to BaseState is needed for doc generation when resolving @@ -2915,9 +2936,9 @@ def BaseState(self) -> "type[BaseState]": # noqa: N802 event = EventNamespace -event.event = event # pyright: ignore[reportAttributeAccessIssue] +event.event = event _this = sys.modules[__name__] -event.__path__ = _this.__path__ # pyright: ignore[reportAttributeAccessIssue] -event.__spec__ = _this.__spec__ # pyright: ignore[reportAttributeAccessIssue] -event.__package__ = _this.__package__ # pyright: ignore[reportAttributeAccessIssue] -sys.modules[__name__] = event # pyright: ignore[reportArgumentType] +event.__path__ = _this.__path__ +event.__spec__ = _this.__spec__ +event.__package__ = _this.__package__ +sys.modules[__name__] = event # ty:ignore[invalid-assignment] diff --git a/packages/reflex-base/src/reflex_base/event/context.py b/packages/reflex-base/src/reflex_base/event/context.py index df3f0200e62..83ee400b5d9 100644 --- a/packages/reflex-base/src/reflex_base/event/context.py +++ b/packages/reflex-base/src/reflex_base/event/context.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, Protocol from reflex_base.context.base import BaseContext -from reflex_base.utils.format import to_snake_case +from reflex_base.utils.format import callable_name, to_snake_case if TYPE_CHECKING: from reflex.istate.manager import StateManager @@ -24,7 +24,7 @@ def get_name(cls: type | Callable) -> str: The name of the state/func. """ module = cls.__module__.replace(".", "___") - qualname = getattr(cls, "__qualname__", cls.__name__).replace(".", "___") + qualname = getattr(cls, "__qualname__", callable_name(cls)).replace(".", "___") return to_snake_case(f"{module}___{qualname}") diff --git a/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py b/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py index c8ad3e5d589..1f7134d76ef 100644 --- a/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py +++ b/packages/reflex-base/src/reflex_base/event/processor/base_state_processor.py @@ -251,7 +251,9 @@ async def process_event( try: while True: await chain_updates( - next(events), root_state=root_state, handler_name=handler_name + next(events), # ty:ignore[invalid-argument-type] + root_state=root_state, + handler_name=handler_name, ) except StopIteration as si: # the "return" value of the generator is not available @@ -391,7 +393,7 @@ async def _handle_backend_exception( if events := self.backend_exception_handler(ex): await chain_updates( events=events, - handler_name=self.backend_exception_handler.__qualname__, + handler_name=self.backend_exception_handler.__qualname__, # ty:ignore[unresolved-attribute] ) diff --git a/packages/reflex-base/src/reflex_base/event/processor/event_processor.py b/packages/reflex-base/src/reflex_base/event/processor/event_processor.py index 7d9296fe4dd..5555848fdc4 100644 --- a/packages/reflex-base/src/reflex_base/event/processor/event_processor.py +++ b/packages/reflex-base/src/reflex_base/event/processor/event_processor.py @@ -32,7 +32,7 @@ if hasattr(asyncio, "QueueShutDown"): - class QueueShutDown(asyncio.QueueShutDown): # pyright: ignore[reportRedeclaration] + class QueueShutDown(asyncio.QueueShutDown): """Exception raised when trying to put an item into a shut down queue.""" else: @@ -586,7 +586,7 @@ def _create_event_task( name=f"reflex_event|{entry.event.name}|{entry.ctx.token}|{time.time()}", ) if sys.version_info < (3, 12): - task._event_ctx = entry.ctx # pyright: ignore[reportAttributeAccessIssue] + task._event_ctx = entry.ctx # ty:ignore[unresolved-attribute] self._tasks[entry.ctx.txid] = task task.add_done_callback(self._finish_task) return task @@ -710,7 +710,7 @@ def _finish_task(self, task: asyncio.Task): if sys.version_info < (3, 12): # py3.11 compat - task_ctx = task._event_ctx # type: ignore[attr-defined] + task_ctx = task._event_ctx # type: ignore[attr-defined] # ty:ignore[unresolved-attribute] else: task_ctx = task.get_context().run(EventContext.get) self._tasks.pop(task_ctx.txid, None) @@ -746,7 +746,7 @@ def _finish_task(self, task: asyncio.Task): name=f"reflex_backend_exception_handler|task=[{task.get_name()}]|{time.time()}", ) if sys.version_info < (3, 12): - t._event_ctx = task_ctx # pyright: ignore[reportAttributeAccessIssue] + t._event_ctx = task_ctx # ty:ignore[unresolved-attribute] t.add_done_callback(self._finish_task) return console.error( diff --git a/packages/reflex-base/src/reflex_base/plugins/compiler.py b/packages/reflex-base/src/reflex_base/plugins/compiler.py index ecb55a03d92..e94cdce7314 100644 --- a/packages/reflex-base/src/reflex_base/plugins/compiler.py +++ b/packages/reflex-base/src/reflex_base/plugins/compiler.py @@ -13,6 +13,7 @@ from typing_extensions import Self from reflex_base.components.component import BaseComponent, Component +from reflex_base.utils.format import callable_name from reflex_base.utils.imports import ParsedImportDict, collapse_imports, merge_imports from reflex_base.vars import VarData @@ -490,7 +491,7 @@ def visit_children( updated_children = list(children[:index]) updated_children.append(compiled_child) if updated_children is None: - return children if isinstance(children, tuple) else tuple(children) + return children if isinstance(children, tuple) else tuple(children) # ty:ignore[invalid-return-type] return tuple(updated_children) def visit( @@ -577,7 +578,7 @@ def _apply_replacement( if replacement is None: return comp, children if isinstance(replacement, tuple): - return replacement + return replacement # ty:ignore[invalid-return-type] return replacement, children @@ -808,7 +809,7 @@ def compile( **kwargs, ) if page_ctx is None: - page_name = getattr(page_fn, "__name__", repr(page_fn)) + page_name = callable_name(page_fn) msg = ( f"No compiler plugin was able to evaluate page {page.route!r} " f"({page_name})." diff --git a/packages/reflex-base/src/reflex_base/plugins/shared_tailwind.py b/packages/reflex-base/src/reflex_base/plugins/shared_tailwind.py index 62180093ee6..e32ddcacc89 100644 --- a/packages/reflex-base/src/reflex_base/plugins/shared_tailwind.py +++ b/packages/reflex-base/src/reflex_base/plugins/shared_tailwind.py @@ -106,7 +106,7 @@ def tailwind_config_js_template( # Extract destructured imports from plugin dicts only imports = [ - plugin["import"] + plugin["import"] # ty:ignore[invalid-argument-type] for plugin in plugins if isinstance(plugin, Mapping) and "import" in plugin ] @@ -121,7 +121,7 @@ def tailwind_config_js_template( for i, plugin in enumerate(plugins, 1): if isinstance(plugin, Mapping) and "call" not in plugin: plugin_imports.append( - f"import plugin{i} from {json.dumps(plugin['name'])};" + f"import plugin{i} from {json.dumps(plugin['name'])};" # ty:ignore[invalid-argument-type] ) elif not isinstance(plugin, Mapping): plugin_imports.append(f"import plugin{i} from {json.dumps(plugin)};") @@ -139,8 +139,8 @@ def tailwind_config_js_template( if isinstance(plugin, Mapping) and "call" in plugin: args_part = "" if "args" in plugin: - args_part = json.dumps(plugin["args"]) - plugin_list.append(f"{plugin['call']}({args_part})") + args_part = json.dumps(plugin["args"]) # ty:ignore[invalid-argument-type, invalid-key] + plugin_list.append(f"{plugin['call']}({args_part})") # ty:ignore[invalid-argument-type, invalid-key] else: plugin_list.append(f"plugin{i}") diff --git a/packages/reflex-base/src/reflex_base/style.py b/packages/reflex-base/src/reflex_base/style.py index d80d650297c..c1c04ce9f6b 100644 --- a/packages/reflex-base/src/reflex_base/style.py +++ b/packages/reflex-base/src/reflex_base/style.py @@ -140,7 +140,7 @@ def convert_item( def convert_list( responsive_list: list[str | dict | Var], -) -> tuple[list[str | dict[str, Var | list | dict]], VarData | None]: +) -> tuple[list[Var | str | dict[str, Var | str | list | dict]], VarData | None]: """Format a responsive value list. Args: @@ -149,10 +149,10 @@ def convert_list( Returns: The recursively converted responsive value list and any associated VarData. """ - converted_value = [] + converted_value: list[Var | str | dict[str, Var | str | list | dict]] = [] item_var_datas = [] for responsive_item in responsive_list: - if isinstance(responsive_item, dict): + if not isinstance(responsive_item, Var) and isinstance(responsive_item, dict): # Recursively format nested style dictionaries. item, item_var_data = convert(responsive_item) else: @@ -163,8 +163,8 @@ def convert_list( def convert( - style_dict: dict[str, Var | dict | list | str], -) -> tuple[dict[str, str | list | dict], VarData | None]: + style_dict: Mapping[str, Any], +) -> tuple[dict[str, Var | str | list | dict], VarData | None]: """Format a style dictionary. Args: @@ -174,7 +174,7 @@ def convert( The formatted style dictionary. """ var_data = None # Track import/hook data from any Vars in the style dict. - out = {} + out: dict[str, Var | str | list | dict] = {} def update_out_dict( return_value: Var | dict | list | str, keys_to_update: tuple[str, ...] @@ -365,7 +365,7 @@ def format_as_emotion(style_dict: dict[str, Any]) -> Style | None: else: # Apply media queries from responsive value list. mbps = { - media_query([0, *breakpoints_values][bp]): ( + media_query([0, *breakpoints_values][bp]): ( # ty:ignore[invalid-argument-type] bp_value if isinstance(bp_value, dict) else {key: bp_value} ) for bp, bp_value in enumerate(value) diff --git a/packages/reflex-base/src/reflex_base/telemetry_context.py b/packages/reflex-base/src/reflex_base/telemetry_context.py index 739b2f7a372..7c3ff3363f4 100644 --- a/packages/reflex-base/src/reflex_base/telemetry_context.py +++ b/packages/reflex-base/src/reflex_base/telemetry_context.py @@ -77,7 +77,7 @@ def set_exception(self, exc: BaseException | None) -> None: object.__setattr__(self, "exception", exc) @classmethod - def get(cls) -> TelemetryContext | None: # pyright: ignore[reportIncompatibleMethodOverride] + def get(cls) -> TelemetryContext | None: """Return the active telemetry context, or None if none is attached. Returns: diff --git a/packages/reflex-base/src/reflex_base/utils/console.py b/packages/reflex-base/src/reflex_base/utils/console.py index 962008e42e0..a46a56aff6a 100644 --- a/packages/reflex-base/src/reflex_base/utils/console.py +++ b/packages/reflex-base/src/reflex_base/utils/console.py @@ -275,7 +275,7 @@ def _exclude_paths_from_frame_info() -> list[Path]: try: import reflex as rx except ImportError: - rx = None + rx = None # ty:ignore[invalid-assignment] # Exclude utility modules that should never be the source of deprecated reflex usage. exclude_modules: list[ModuleType | None] = [ diff --git a/packages/reflex-base/src/reflex_base/utils/decorator.py b/packages/reflex-base/src/reflex_base/utils/decorator.py index f1b31419fbc..8a99c6a68f0 100644 --- a/packages/reflex-base/src/reflex_base/utils/decorator.py +++ b/packages/reflex-base/src/reflex_base/utils/decorator.py @@ -5,6 +5,8 @@ from pathlib import Path from typing import ParamSpec, TypeVar, cast +from reflex_base.utils.format import callable_name + T = TypeVar("T") @@ -24,7 +26,7 @@ def once(f: Callable[[], T]) -> Callable[[], T]: def wrapper() -> T: nonlocal value value = f() if value is unset else value - return value # pyright: ignore[reportReturnType] + return value # ty:ignore[invalid-return-type] return wrapper @@ -61,12 +63,13 @@ def debug(f: Callable[P, T]) -> Callable[P, T]: Returns: A function that prints the function name, arguments, and result. """ + fn_name = callable_name(f) @functools.wraps(f) def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: result = f(*args, **kwargs) print( # noqa: T201 - f"Calling {f.__name__} with args: {args} and kwargs: {kwargs}, result: {result}" + f"Calling {fn_name} with args: {args} and kwargs: {kwargs}, result: {result}" ) return result @@ -108,7 +111,9 @@ def cached_procedure( The decorated function. """ - def _inner_decorator(func: Callable[P, Picklable]) -> Callable[P, Picklable]: + def _inner_decorator(func: Callable[P, Picklable]) -> Callable[P, Picklable]: # ty:ignore[invalid-type-form] + fn_name = callable_name(func) + def _inner(*args: P.args, **kwargs: P.kwargs) -> Picklable: cache_file = cache_file_path() @@ -123,7 +128,7 @@ def _inner(*args: P.args, **kwargs: P.kwargs) -> Picklable: from reflex_base.utils import console console.debug( - f"Using cached value for {func.__name__} with payload: {new_payload}" + f"Using cached value for {fn_name} with payload: {new_payload}" ) return cast("Picklable", value) diff --git a/packages/reflex-base/src/reflex_base/utils/format.py b/packages/reflex-base/src/reflex_base/utils/format.py index c8f11e01f02..9ea5881d447 100644 --- a/packages/reflex-base/src/reflex_base/utils/format.py +++ b/packages/reflex-base/src/reflex_base/utils/format.py @@ -32,6 +32,21 @@ } +def callable_name(fn: object) -> str: + """Return ``fn.__name__`` when available, otherwise ``repr(fn)``. + + Args: + fn: The object whose display name is wanted. + + Returns: + The display name. + """ + name = getattr(fn, "__name__", None) + if isinstance(name, str): + return name + return repr(fn) + + def length_of_largest_common_substring(str1: str, str2: str) -> int: """Find the length of the largest common substring between two strings. @@ -404,7 +419,7 @@ def format_prop( # For dictionaries, convert any properties to strings. if isinstance(prop, dict): - prop = serializers.serialize_dict(prop) # pyright: ignore [reportAttributeAccessIssue] + prop = serializers.serialize_dict(prop) # ty:ignore[unresolved-attribute] else: # Dump the prop as JSON. @@ -577,7 +592,7 @@ def _default_args_spec(): if isinstance(spec, (EventHandler, EventSpec)): specs = [call_event_handler(spec, args_spec or _default_args_spec)] elif isinstance(spec, type(lambda: None)): - specs = call_event_fn(spec, args_spec or _default_args_spec) # pyright: ignore [reportAssignmentType, reportArgumentType] + specs = call_event_fn(spec, args_spec or _default_args_spec) # ty:ignore[invalid-assignment] if isinstance(specs, Var): msg = f"Invalid event spec: {specs}. Expected a list of EventSpecs." raise ValueError(msg) diff --git a/packages/reflex-base/src/reflex_base/utils/imports.py b/packages/reflex-base/src/reflex_base/utils/imports.py index e4ec1935739..d48646b514d 100644 --- a/packages/reflex-base/src/reflex_base/utils/imports.py +++ b/packages/reflex-base/src/reflex_base/utils/imports.py @@ -50,7 +50,7 @@ def merge_imports( if isinstance(fields, (list, tuple, set)): all_imports[lib].extend( ImportVar(field) if isinstance(field, str) else field - for field in fields + for field in fields # ty:ignore[invalid-argument-type] ) else: all_imports[lib].append( diff --git a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py index 0425f03d7b1..6fb84465a4b 100644 --- a/packages/reflex-base/src/reflex_base/utils/pyi_generator.py +++ b/packages/reflex-base/src/reflex_base/utils/pyi_generator.py @@ -490,7 +490,7 @@ def _get_class_event_triggers(target_class: type) -> frozenset[str]: Returns: The event trigger names defined on the class. """ - return frozenset(target_class.get_event_triggers()) + return frozenset(target_class.get_event_triggers()) # ty:ignore[unresolved-attribute] def _generate_imports( @@ -506,7 +506,7 @@ def _generate_imports( """ return [ *[ - ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) # pyright: ignore [reportCallIssue] + ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) # ty:ignore[no-matching-overload] for name, values in DEFAULT_IMPORTS.items() ], ast.Import([ast.alias("reflex")]), @@ -641,7 +641,7 @@ def _extract_class_props_as_ast_nodes( # with the annotation in some cases. with contextlib.suppress(AttributeError, KeyError): # Try to get default from pydantic field definition. - default = target_class.__fields__[name].default + default = target_class.__fields__[name].default # ty:ignore[unresolved-attribute] if isinstance(default, Var): default = default._decode() @@ -658,7 +658,7 @@ def _extract_class_props_as_ast_nodes( ) ), ), - ast.Constant(value=default), # pyright: ignore [reportArgumentType] + ast.Constant(value=default), )) return kwargs @@ -682,7 +682,8 @@ def _get_visible_type_name( type_name = getattr(typ, "__name__", None) if type_name is not None and ( - type_hint_globals.get(type_name) is typ + type_module in ("builtins", "__builtins__") + or type_hint_globals.get(type_name) is typ or type_name in DEFAULT_IMPORTS.get(str(type_module), set()) or type_name in EXCLUDED_IMPORTS.get(str(type_module), set()) ): @@ -746,7 +747,9 @@ def type_to_ast( return ast.Name(id=str(typ)) # Get the base type name (List, Dict, Optional, etc.) - base_name = getattr(origin, "_name", origin.__name__) + base_name = getattr(origin, "_name", None) or getattr( + origin, "__name__", repr(origin) + ) # Get type arguments args = get_args(typ) @@ -837,7 +840,9 @@ def _generate_component_create_functiondef( # kwargs associated with props defined in the class and its parents all_classes = [c for c in clz.__mro__ if issubclass(c, Component)] prop_kwargs = _extract_class_props_as_ast_nodes( - clz.create, all_classes, type_hint_globals + clz.create, + all_classes, # ty:ignore[invalid-argument-type] + type_hint_globals, ) all_props = [arg[0].arg for arg in prop_kwargs] kwargs.extend(prop_kwargs) @@ -964,7 +969,7 @@ def figure_out_return_type(annotation: Any): defaults=[], ) - return ast.FunctionDef( # pyright: ignore [reportCallIssue] + return ast.FunctionDef( name="create", args=create_args, body=[ @@ -1016,7 +1021,7 @@ def _generate_staticmethod_call_functiondef( else [] ), ) - return ast.FunctionDef( # pyright: ignore [reportCallIssue] + return ast.FunctionDef( name="__call__", args=call_args, body=[ @@ -1067,7 +1072,7 @@ def _generate_namespace_call_functiondef( # Determine which class is wrapped by the namespace __call__ method component_clz = clz.__call__.__self__ - if clz.__call__.__func__.__name__ != "create": # pyright: ignore [reportFunctionMemberAccess] + if clz.__call__.__func__.__name__ != "create": return None if not issubclass(component_clz, Component): @@ -1158,7 +1163,7 @@ def visit_Module(self, node: ast.Module) -> ast.Module: The modified Module node. """ self.generic_visit(node) - return self._remove_docstring(node) # pyright: ignore [reportReturnType] + return self._remove_docstring(node) # ty:ignore[invalid-return-type] def visit_Import( self, node: ast.Import | ast.ImportFrom diff --git a/packages/reflex-base/src/reflex_base/utils/serializers.py b/packages/reflex-base/src/reflex_base/utils/serializers.py index d20a29e3890..c30d4b02a85 100644 --- a/packages/reflex-base/src/reflex_base/utils/serializers.py +++ b/packages/reflex-base/src/reflex_base/utils/serializers.py @@ -93,7 +93,7 @@ def wrapper(fn: SERIALIZED_FUNCTION) -> SERIALIZED_FUNCTION: # Make sure the type is not already registered. registered_fn = SERIALIZERS.get(type_) if registered_fn is not None and registered_fn != fn and overwrite is not True: - message = f"Overwriting serializer for type {type_} from {registered_fn.__module__}:{registered_fn.__qualname__} to {fn.__module__}:{fn.__qualname__}." + message = f"Overwriting serializer for type {type_} from {registered_fn.__module__}:{registered_fn.__qualname__} to {fn.__module__}:{fn.__qualname__}." # ty:ignore[unresolved-attribute] if overwrite is False: raise ValueError(message) caller_frame = next( @@ -494,7 +494,7 @@ def serialize_image(image: Img) -> str: base64_image = base64.b64encode(image_bytes).decode("utf-8") try: # Newer method to get the mime type, but does not always work. - mime_type = image.get_format_mimetype() # pyright: ignore [reportAttributeAccessIssue] + mime_type = image.get_format_mimetype() # ty:ignore[unresolved-attribute] except AttributeError: try: # Fallback method diff --git a/packages/reflex-base/src/reflex_base/utils/types.py b/packages/reflex-base/src/reflex_base/utils/types.py index feeb3b0da50..e95037087e5 100644 --- a/packages/reflex-base/src/reflex_base/utils/types.py +++ b/packages/reflex-base/src/reflex_base/utils/types.py @@ -25,9 +25,9 @@ Tuple, TypeVar, Union, - _eval_type, # pyright: ignore [reportAttributeAccessIssue] - _GenericAlias, # pyright: ignore [reportAttributeAccessIssue] - _SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue] + _eval_type, # ty:ignore[unresolved-import] + _GenericAlias, # ty:ignore[unresolved-import] + _SpecialGenericAlias, # ty:ignore[unresolved-import] get_args, is_typeddict, ) @@ -71,24 +71,24 @@ def __call__(self) -> Sequence[Var]: ... class _ArgsSpec1(Protocol): - def __call__(self, var1: VAR1, /) -> Sequence[Var]: ... # pyright: ignore [reportInvalidTypeVarUse] + def __call__(self, var1: VAR1, /) -> Sequence[Var]: ... class _ArgsSpec2(Protocol): - def __call__(self, var1: VAR1, var2: VAR2, /) -> Sequence[Var]: ... # pyright: ignore [reportInvalidTypeVarUse] + def __call__(self, var1: VAR1, var2: VAR2, /) -> Sequence[Var]: ... class _ArgsSpec3(Protocol): - def __call__(self, var1: VAR1, var2: VAR2, var3: VAR3, /) -> Sequence[Var]: ... # pyright: ignore [reportInvalidTypeVarUse] + def __call__(self, var1: VAR1, var2: VAR2, var3: VAR3, /) -> Sequence[Var]: ... class _ArgsSpec4(Protocol): def __call__( self, - var1: VAR1, # pyright: ignore [reportInvalidTypeVarUse] - var2: VAR2, # pyright: ignore [reportInvalidTypeVarUse] - var3: VAR3, # pyright: ignore [reportInvalidTypeVarUse] - var4: VAR4, # pyright: ignore [reportInvalidTypeVarUse] + var1: VAR1, + var2: VAR2, + var3: VAR3, + var4: VAR4, /, ) -> Sequence[Var]: ... @@ -96,11 +96,11 @@ def __call__( class _ArgsSpec5(Protocol): def __call__( self, - var1: VAR1, # pyright: ignore [reportInvalidTypeVarUse] - var2: VAR2, # pyright: ignore [reportInvalidTypeVarUse] - var3: VAR3, # pyright: ignore [reportInvalidTypeVarUse] - var4: VAR4, # pyright: ignore [reportInvalidTypeVarUse] - var5: VAR5, # pyright: ignore [reportInvalidTypeVarUse] + var1: VAR1, + var2: VAR2, + var3: VAR3, + var4: VAR4, + var5: VAR5, /, ) -> Sequence[Var]: ... @@ -108,12 +108,12 @@ def __call__( class _ArgsSpec6(Protocol): def __call__( self, - var1: VAR1, # pyright: ignore [reportInvalidTypeVarUse] - var2: VAR2, # pyright: ignore [reportInvalidTypeVarUse] - var3: VAR3, # pyright: ignore [reportInvalidTypeVarUse] - var4: VAR4, # pyright: ignore [reportInvalidTypeVarUse] - var5: VAR5, # pyright: ignore [reportInvalidTypeVarUse] - var6: VAR6, # pyright: ignore [reportInvalidTypeVarUse] + var1: VAR1, + var2: VAR2, + var3: VAR3, + var4: VAR4, + var5: VAR5, + var6: VAR6, /, ) -> Sequence[Var]: ... @@ -121,13 +121,13 @@ def __call__( class _ArgsSpec7(Protocol): def __call__( self, - var1: VAR1, # pyright: ignore [reportInvalidTypeVarUse] - var2: VAR2, # pyright: ignore [reportInvalidTypeVarUse] - var3: VAR3, # pyright: ignore [reportInvalidTypeVarUse] - var4: VAR4, # pyright: ignore [reportInvalidTypeVarUse] - var5: VAR5, # pyright: ignore [reportInvalidTypeVarUse] - var6: VAR6, # pyright: ignore [reportInvalidTypeVarUse] - var7: VAR7, # pyright: ignore [reportInvalidTypeVarUse] + var1: VAR1, + var2: VAR2, + var3: VAR3, + var4: VAR4, + var5: VAR5, + var6: VAR6, + var7: VAR7, /, ) -> Sequence[Var]: ... @@ -232,7 +232,7 @@ def get_type_hints(obj: Any) -> dict[str, Any]: def _unionize(args: list[GenericType]) -> GenericType: if not args: - return Any # pyright: ignore [reportReturnType] + return Any if len(args) == 1: return args[0] return Union[tuple(args)] # noqa: UP007 @@ -303,8 +303,9 @@ def has_args(cls: type) -> bool: return True # Check if the class inherits from a generic class (using __orig_bases__) - if hasattr(cls, "__orig_bases__"): - for base in cls.__orig_bases__: + orig_bases = getattr(cls, "__orig_bases__", None) + if orig_bases is not None: + for base in orig_bases: if get_args(base): return True @@ -461,13 +462,13 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None if type_ is not None: if hasattr(column_type, "item_type"): try: - item_type = column_type.item_type.python_type # pyright: ignore [reportAttributeAccessIssue] + item_type = column_type.item_type.python_type except NotImplementedError: item_type = None if item_type is not None: if type_ in PrimitiveToAnnotation: type_ = PrimitiveToAnnotation[type_] - type_ = type_[item_type] # pyright: ignore [reportIndexIssue] + type_ = type_[item_type] if hasattr(column, "nullable") and column.nullable: type_ = type_ | None return type_ @@ -485,8 +486,8 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None return list[ get_attribute_access_type( attr.target_class, - attr.remote_attr.key, # pyright: ignore [reportAttributeAccessIssue] - ) + attr.remote_attr.key, + ) # ty:ignore[invalid-type-form] ] elif ( isinstance(cls, type) @@ -494,7 +495,7 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None and issubclass(cls, sqlmodel_types) ): # Check in the annotations directly (for sqlmodel.Relationship) - hints = get_type_hints(cls) # pyright: ignore [reportArgumentType] + hints = get_type_hints(cls) if name in hints: type_ = hints[name] type_origin = get_origin(type_) @@ -510,7 +511,7 @@ def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None # Bare class exceptions = NameError try: - hints = get_type_hints(cls) # pyright: ignore [reportArgumentType] + hints = get_type_hints(cls) if name in hints: return hints[name] except exceptions as e: @@ -540,7 +541,7 @@ def get_base_class(cls: GenericType) -> type: return type(get_args(cls)[0]) if is_union(cls): - return tuple(get_base_class(arg) for arg in get_args(cls)) # pyright: ignore [reportReturnType] + return tuple(get_base_class(arg) for arg in get_args(cls)) # ty:ignore[invalid-return-type] return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls @@ -929,13 +930,14 @@ def validate_literal(key: str, value: Any, expected_type: type, comp_name: str): """ from reflex_base.vars import Var + expected_args = get_args(expected_type) if ( is_literal(expected_type) and not isinstance(value, Var) # validating vars is not supported yet. and not is_encoded_fstring(value) # f-strings are not supported. - and value not in expected_type.__args__ + and value not in expected_args ): - allowed_values = expected_type.__args__ + allowed_values = expected_args if value not in allowed_values: allowed_value_str = ",".join([ str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values @@ -1104,7 +1106,7 @@ def typehint_issubclass( def resolve_annotations( raw_annotations: Mapping[str, type[Any]], module_name: str | None -) -> dict[str, type[Any]]: +) -> dict[str, type[Any] | ForwardRef]: """Partially taken from typing.get_type_hints. Resolve string or ForwardRef annotations into type objects if possible. @@ -1114,7 +1116,9 @@ def resolve_annotations( module_name: The name of the module. Returns: - The resolved annotations. + The resolved annotations. Entries that could not be resolved remain + as ``ForwardRef`` instances (callers can re-resolve them later via + ``update_forward_refs``). """ module = sys.modules.get(module_name, None) if module_name is not None else None @@ -1122,7 +1126,7 @@ def resolve_annotations( module.__dict__ if module is not None else None ) - annotations = {} + annotations: dict[str, type[Any] | ForwardRef] = {} for name, value in raw_annotations.items(): if isinstance(value, str): if sys.version_info == (3, 10, 0): diff --git a/packages/reflex-base/src/reflex_base/vars/base.py b/packages/reflex-base/src/reflex_base/vars/base.py index 0181b2774ea..7a46dc26c22 100644 --- a/packages/reflex-base/src/reflex_base/vars/base.py +++ b/packages/reflex-base/src/reflex_base/vars/base.py @@ -2,6 +2,7 @@ from __future__ import annotations +import builtins import contextlib import copy import dataclasses @@ -52,7 +53,7 @@ VarDependencyError, VarTypeError, ) -from reflex_base.utils.format import format_state_name +from reflex_base.utils.format import callable_name, format_state_name from reflex_base.utils.imports import ( ImmutableImportDict, ImmutableParsedImportDict, @@ -179,7 +180,7 @@ def __init__( if hooks and any(hooks.values()): # Merge our dependencies first, so they can be referenced. - merged_var_data = VarData.merge(*hooks.values(), self) + merged_var_data = VarData.merge(*hooks.values(), self) # ty:ignore[invalid-argument-type] if merged_var_data is not None: object.__setattr__(self, "state", merged_var_data.state) object.__setattr__(self, "field_name", merged_var_data.field_name) @@ -410,7 +411,7 @@ def __str__(self) -> str: return self._js_expr @property - def _var_is_local(self) -> bool: + def _var_is_local(self) -> builtins.bool: """Whether this is a local javascript variable. Returns: @@ -419,7 +420,7 @@ def _var_is_local(self) -> bool: return False @property - def _var_is_string(self) -> bool: + def _var_is_string(self) -> builtins.bool: """Whether the var is a string literal. Returns: @@ -456,7 +457,7 @@ def __init_subclass__( frozen=True, slots=True, ) - class ToVarOperation(ToOperation, cls): + class ToVarOperation(ToOperation, cls): # ty:ignore[shadowed-type-variable] """Base class of converting a var to another var type.""" _original: Var = dataclasses.field( @@ -525,7 +526,7 @@ def __deepcopy__(self, memo: dict[int, Any]) -> Self: """ return self - def equals(self, other: Var) -> bool: + def equals(self, other: Var) -> builtins.bool: """Check if two vars are equal. Args: @@ -602,7 +603,7 @@ def _replace( @overload @classmethod - def create( # pyright: ignore[reportOverlappingOverload] + def create( cls, value: NoReturn, _var_data: VarData | None = None, @@ -610,9 +611,9 @@ def create( # pyright: ignore[reportOverlappingOverload] @overload @classmethod - def create( # pyright: ignore[reportOverlappingOverload] + def create( cls, - value: bool, + value: builtins.bool, _var_data: VarData | None = None, ) -> LiteralBooleanVar: ... @@ -642,7 +643,7 @@ def create( @overload @classmethod - def create( # pyright: ignore [reportOverlappingOverload] + def create( cls, value: Color, _var_data: VarData | None = None, @@ -650,7 +651,7 @@ def create( # pyright: ignore [reportOverlappingOverload] @overload @classmethod - def create( # pyright: ignore [reportOverlappingOverload] + def create( cls, value: LITERAL_STRING_T, _var_data: VarData | None = None, @@ -658,7 +659,7 @@ def create( # pyright: ignore [reportOverlappingOverload] @overload @classmethod - def create( # pyright: ignore [reportOverlappingOverload] + def create( cls, value: STRING_T, _var_data: VarData | None = None, @@ -666,7 +667,7 @@ def create( # pyright: ignore [reportOverlappingOverload] @overload @classmethod - def create( # pyright: ignore[reportOverlappingOverload] + def create( cls, value: None, _var_data: VarData | None = None, @@ -713,7 +714,7 @@ def create( """ # If the value is already a var, do nothing. if isinstance(value, Var): - return value + return value # ty:ignore[invalid-return-type] return LiteralVar.create(value, _var_data=_var_data) @@ -734,10 +735,10 @@ def __format__(self, format_spec: str) -> str: return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}" @overload - def to(self, output: type[str]) -> StringVar: ... # pyright: ignore[reportOverlappingOverload] + def to(self, output: type[str]) -> StringVar: ... @overload - def to(self, output: type[bool]) -> BooleanVar: ... + def to(self, output: type[builtins.bool]) -> BooleanVar: ... @overload def to(self, output: type[int]) -> NumberVar[int]: ... @@ -806,7 +807,7 @@ def to( return self.to(var_subclass.var_subclass, output) if fixed_output_type is None: - return get_to_operation(NoneVar).create(self) # pyright: ignore [reportReturnType] + return get_to_operation(NoneVar).create(self) # Handle fixed_output_type being Base or a dataclass. if can_use_in_object_var(output): @@ -820,7 +821,7 @@ def to( new_var_type = var_type else: new_var_type = var_type or current_var_type - return var_subclass.to_var_subclass.create( # pyright: ignore [reportReturnType] + return var_subclass.to_var_subclass.create( value=self, _var_type=new_var_type ) @@ -841,13 +842,13 @@ def to( return self @overload - def guess_type(self: Var[NoReturn]) -> Var[Any]: ... # pyright: ignore [reportOverlappingOverload] + def guess_type(self: Var[NoReturn]) -> Var[Any]: ... @overload def guess_type(self: Var[str]) -> StringVar: ... @overload - def guess_type(self: Var[bool]) -> BooleanVar: ... + def guess_type(self: Var[builtins.bool]) -> BooleanVar: ... @overload def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ... @@ -985,13 +986,13 @@ def _var_set_state(self, state: type[BaseState] | str) -> Self: else format_state_name(state.get_full_name()) ) - return StateOperation.create( # pyright: ignore [reportReturnType] + return StateOperation.create( formatted_state_name, self, _var_data=VarData.merge( VarData.from_state(state, self._js_expr), self._var_data ), - ).guess_type() + ).guess_type() # ty:ignore[invalid-return-type] def __eq__(self, other: Var | Any) -> BooleanVar: """Check if the current variable is equal to the given variable. @@ -1109,7 +1110,7 @@ def __invert__(self) -> BooleanVar: """ return ~self.bool() - def to_string(self, use_json: bool = True) -> StringVar: + def to_string(self, use_json: builtins.bool = True) -> StringVar: """Convert the var to a string. Args: @@ -1326,9 +1327,18 @@ def __contains__(self, _: Any) -> Var: VAR_INSIDE = TypeVar("VAR_INSIDE") +@dataclasses.dataclass(eq=False, frozen=True) class ToOperation: """A var operation that converts a var to another type.""" + _js_expr: str = "" + _var_type: GenericType = Any + _var_data: VarData | None = None + _original: Var = dataclasses.field( + default_factory=lambda: Var(_js_expr="null", _var_type=None) + ) + _default_var_type: ClassVar[GenericType] = Any + def __getattr__(self, name: str) -> Any: """Get an attribute of the var. @@ -1385,10 +1395,10 @@ def create( The ToOperation. """ return cls( - _js_expr="", # pyright: ignore [reportCallIssue] - _var_data=_var_data, # pyright: ignore [reportCallIssue] - _var_type=_var_type or cls._default_var_type, # pyright: ignore [reportCallIssue, reportAttributeAccessIssue] - _original=value, # pyright: ignore [reportCallIssue] + _js_expr="", + _var_data=_var_data, + _var_type=_var_type or cls._default_var_type, + _original=value, ) @@ -1649,7 +1659,7 @@ def get_python_literal(value: LiteralVar | Any) -> Any | None: # NoReturn is used to match CustomVarOperationReturn with no type hint. @overload -def var_operation( # pyright: ignore [reportOverlappingOverload] +def var_operation( func: Callable[P, CustomVarOperationReturn[NoReturn]], ) -> Callable[P, Var]: ... @@ -1661,7 +1671,7 @@ def var_operation( @overload -def var_operation( # pyright: ignore [reportOverlappingOverload] +def var_operation( func: Callable[P, CustomVarOperationReturn[bool]] | Callable[P, CustomVarOperationReturn[bool | None]], ) -> Callable[P, BooleanVar]: ... @@ -1711,7 +1721,7 @@ def var_operation( ) -> Callable[P, Var[T]]: ... -def var_operation( # pyright: ignore [reportInconsistentOverload] +def var_operation( func: Callable[P, CustomVarOperationReturn[T]], ) -> Callable[P, Var[T]]: """Decorator for creating a var operation. @@ -1743,9 +1753,9 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]: } return CustomVarOperation.create( - name=func.__name__, + name=callable_name(func), args=tuple(list(args_vars.items()) + list(kwargs_vars.items())), - return_var=func(*args_vars.values(), **kwargs_vars), # pyright: ignore [reportCallIssue, reportReturnType] + return_var=func(*args_vars.values(), **kwargs_vars), # ty:ignore[invalid-argument-type] ).guess_type() return wrapper @@ -1768,21 +1778,21 @@ def figure_out_type(value: Any) -> types.GenericType: if isinstance(value, list): if not value: return Sequence[NoReturn] - return Sequence[unionize(*{figure_out_type(v) for v in value[:100]})] + return Sequence[unionize(*{figure_out_type(v) for v in value[:100]})] # ty:ignore[invalid-type-form] if isinstance(value, set): - return set[unionize(*{figure_out_type(v) for v in value})] + return set[unionize(*{figure_out_type(v) for v in value})] # ty:ignore[invalid-type-form] if isinstance(value, tuple): if not value: return tuple[NoReturn, ...] if len(value) <= 5: - return tuple[tuple(figure_out_type(v) for v in value)] - return tuple[unionize(*{figure_out_type(v) for v in value[:100]}), ...] + return tuple[tuple(figure_out_type(v) for v in value)] # ty:ignore[invalid-type-form] + return tuple[unionize(*{figure_out_type(v) for v in value[:100]}), ...] # ty:ignore[invalid-type-form] if isinstance(value, Mapping): if not value: return Mapping[NoReturn, NoReturn] return Mapping[ - unionize(*{figure_out_type(k) for k in list(value.keys())[:100]}), - unionize(*{figure_out_type(v) for v in list(value.values())[:100]}), + unionize(*{figure_out_type(k) for k in list(value.keys())[:100]}), # ty:ignore[invalid-type-form] + unionize(*{figure_out_type(v) for v in list(value.values())[:100]}), # ty:ignore[invalid-type-form] ] return type(value) @@ -1912,7 +1922,7 @@ def __getattr__(self, name: str) -> Any: next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1] - return next_class.__getattr__(self, name) + return next_class.__getattr__(self, name) # ty:ignore[unresolved-attribute] def _get_all_var_data(self) -> VarData | None: """Get all VarData associated with the Var. @@ -2084,7 +2094,7 @@ class ComputedVar(Var[RETURN_TYPE]): _fget: Callable[[BaseState], RETURN_TYPE] = dataclasses.field( default_factory=lambda: lambda _: None - ) # pyright: ignore [reportAssignmentType] + ) # ty:ignore[invalid-assignment] _name: str = dataclasses.field(default="") @@ -2119,10 +2129,11 @@ def __init__( "return", Any ) + fget_name = callable_name(fget) if hint is Any: - raise UntypedComputedVarError(var_name=fget.__name__) + raise UntypedComputedVarError(var_name=fget_name) is_using_fget_name = "_js_expr" not in kwargs - js_expr = kwargs.pop("_js_expr", fget.__name__ + FIELD_MARKER) + js_expr = kwargs.pop("_js_expr", fget_name + FIELD_MARKER) kwargs.setdefault("_var_type", hint) Var.__init__( @@ -2131,7 +2142,7 @@ def __init__( _var_type=kwargs.pop("_var_type"), _var_data=kwargs.pop( "_var_data", - VarData(field_name=fget.__name__) if is_using_fget_name else None, + VarData(field_name=fget_name) if is_using_fget_name else None, ), ) @@ -2140,12 +2151,12 @@ def __init__( raise TypeError(msg) if backend is None: - backend = fget.__name__.startswith("_") + backend = fget_name.startswith("_") object.__setattr__(self, "_backend", backend) object.__setattr__(self, "_initial_value", initial_value) object.__setattr__(self, "_cache", cache) - object.__setattr__(self, "_name", fget.__name__) + object.__setattr__(self, "_name", fget_name) if isinstance(interval, int): interval = datetime.timedelta(seconds=interval) @@ -2356,7 +2367,7 @@ def __get__(self, instance: None, owner: type) -> ComputedVar[RETURN_TYPE]: ... @overload def __get__(self, instance: BaseState, owner: type) -> RETURN_TYPE: ... - def __get__(self, instance: BaseState | None, owner: type): + def __get__(self, instance: BaseState | None, owner: type[BaseState]): """Get the ComputedVar value. If the value is already cached on the instance, return the cached value. @@ -2371,7 +2382,10 @@ def __get__(self, instance: BaseState | None, owner: type): if instance is None: state_where_defined = owner while self._name in state_where_defined.inherited_vars: - state_where_defined = state_where_defined.get_parent_state() + parent = state_where_defined.get_parent_state() + if parent is None: + break + state_where_defined = parent field_name = ( format_state_name(state_where_defined.get_full_name()) @@ -2432,12 +2446,11 @@ def _deps( """ from .dep_tracking import DependencyTracker - d = {} + d: dict[str, set[str]] = {} if self._static_deps: - d.update(self._static_deps) # None is a placeholder for the current state class. - if None in d: - d[objclass.get_full_name()] = d.pop(None) + for k, v in self._static_deps.items(): + d[k if k is not None else objclass.get_full_name()] = v if not self._auto_deps: return d @@ -2518,7 +2531,7 @@ def _determine_var_type(self) -> type: hints = get_type_hints(self._fget) if "return" in hints: return hints["return"] - return Any # pyright: ignore [reportReturnType] + return Any @property def __class__(self) -> type: @@ -2780,7 +2793,7 @@ def computed_var( if fget is not None: sign = inspect.signature(fget) if len(sign.parameters) != 1: - raise ComputedVarSignatureError(fget.__name__, signature=str(sign)) + raise ComputedVarSignatureError(callable_name(fget), signature=str(sign)) if inspect.iscoroutinefunction(fget): computed_var_cls = AsyncComputedVar @@ -3149,15 +3162,16 @@ def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]: return_type = types["return"] origin = get_origin(return_type) + fn_name = callable_name(fn) if origin is not Var: - msg = f"Expected return type of {fn.__name__} to be a Var, got {origin}." + msg = f"Expected return type of {fn_name} to be a Var, got {origin}." raise TypeError(msg) generic_args = get_args(return_type) if not generic_args: - msg = f"Expected Var return type of {fn.__name__} to have a generic type." + msg = f"Expected Var return type of {fn_name} to have a generic type." raise TypeError(msg) generic_type = get_origin(generic_args[0]) or generic_args[0] @@ -3198,6 +3212,7 @@ def dispatch( if result_origin_var_type in dispatchers: fn = dispatchers[result_origin_var_type] + fn_name = callable_name(fn) fn_types = get_type_hints(fn) fn_first_arg_type = fn_types.get( next(iter(inspect.signature(fn).parameters.values())).name, Any @@ -3208,7 +3223,7 @@ def dispatch( fn_return_origin = get_origin(fn_return) or fn_return if fn_return_origin is not Var: - msg = f"Expected return type of {fn.__name__} to be a Var, got {fn_return}." + msg = f"Expected return type of {fn_name} to be a Var, got {fn_return}." raise TypeError(msg) fn_return_generic_args = get_args(fn_return) @@ -3220,7 +3235,7 @@ def dispatch( arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type if arg_origin is not Var: - msg = f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}." + msg = f"Expected first argument of {fn_name} to be a Var, got {fn_first_arg_type}." raise TypeError(msg) arg_generic_args = get_args(fn_first_arg_type) @@ -3286,8 +3301,7 @@ def __init__( default: FIELD_TYPE | _MISSING_TYPE = MISSING, default_factory: Callable[[], FIELD_TYPE] | None = None, is_var: bool = True, - annotated_type: GenericType # pyright: ignore [reportRedeclaration] - | _MISSING_TYPE = MISSING, + annotated_type: GenericType | _MISSING_TYPE = MISSING, ) -> None: """Initialize the field. @@ -3311,7 +3325,7 @@ def __init__( if self.default is MISSING and self.default_factory is None: default_value = types.get_default_value_for_type(annotated_type) if default_value is None and not types.is_optional(annotated_type): - annotated_type = annotated_type | None + annotated_type = annotated_type | None # ty:ignore[conflicting-declarations] if types.is_immutable(default_value): self.default = default_value else: @@ -3321,7 +3335,7 @@ def __init__( self.outer_type_ = self.annotated_type = annotated_type if type_origin is Annotated: - type_origin = annotated_type.__origin__ # pyright: ignore [reportAttributeAccessIssue] + type_origin = annotated_type.__origin__ self.type_ = self.type_origin = type_origin else: @@ -3444,7 +3458,7 @@ def __get__(self, instance: None, owner: Any) -> Var[FIELD_TYPE]: ... @overload def __get__(self, instance: Any, owner: Any) -> FIELD_TYPE: ... - def __get__(self, instance: Any, owner: Any): # pyright: ignore [reportInconsistentOverload] + def __get__(self, instance: Any, owner: Any): """Get the Var. Args: @@ -3459,7 +3473,7 @@ def field( *, is_var: Literal[False], default_factory: Callable[[], FIELD_TYPE] | None = None, -) -> FIELD_TYPE: ... +) -> Any: ... @overload @@ -3468,7 +3482,7 @@ def field( *, default_factory: Callable[[], FIELD_TYPE] | None = None, is_var: Literal[True] = True, -) -> Field[FIELD_TYPE]: ... +) -> Any: ... def field( @@ -3641,6 +3655,11 @@ def __new__( class EvenMoreBasicBaseState(metaclass=BaseStateMeta): """A simplified base state class that provides basic functionality.""" + if TYPE_CHECKING: + # Whether this state class is a mixin and should not be instantiated. + # Set by ``BaseStateMeta.__new__`` as a class attribute. + _mixin: ClassVar[bool] = False + def __init__( self, **kwargs, diff --git a/packages/reflex-base/src/reflex_base/vars/dep_tracking.py b/packages/reflex-base/src/reflex_base/vars/dep_tracking.py index b8642d2ef6e..60ff649b5e1 100644 --- a/packages/reflex-base/src/reflex_base/vars/dep_tracking.py +++ b/packages/reflex-base/src/reflex_base/vars/dep_tracking.py @@ -105,10 +105,10 @@ def __post_init__(self): """After initializing, populate the dependencies dict.""" with contextlib.suppress(AttributeError): # unbox functools.partial - self.func = cast(FunctionType, self.func.func) # pyright: ignore[reportAttributeAccessIssue] + self.func = cast(FunctionType, self.func.func) # ty:ignore[unresolved-attribute] with contextlib.suppress(AttributeError): # unbox EventHandler - self.func = cast(FunctionType, self.func.fn) # pyright: ignore[reportAttributeAccessIssue,reportFunctionMemberAccess] + self.func = cast(FunctionType, self.func.fn) # ty:ignore[unresolved-attribute] if isinstance(self.func, FunctionType): with contextlib.suppress(AttributeError, IndexError): @@ -216,7 +216,7 @@ def _get_globals(self) -> dict[str, Any]: """ if isinstance(self.func, CodeType): return {} - return self.func.__globals__ # pyright: ignore[reportAttributeAccessIssue] + return self.func.__globals__ def _get_closure(self) -> dict[str, Any]: """Get the closure of the function, with unbound values omitted. @@ -229,7 +229,7 @@ def _get_closure(self) -> dict[str, Any]: return { var_name: get_cell_value(cell) for var_name, cell in zip( - self.func.__code__.co_freevars, # pyright: ignore[reportAttributeAccessIssue] + self.func.__code__.co_freevars, self.func.__closure__ or (), strict=False, ) diff --git a/packages/reflex-base/src/reflex_base/vars/function.py b/packages/reflex-base/src/reflex_base/vars/function.py index 85a311c58b5..d72baa247e3 100644 --- a/packages/reflex-base/src/reflex_base/vars/function.py +++ b/packages/reflex-base/src/reflex_base/vars/function.py @@ -176,7 +176,7 @@ def partial( @overload def partial(self, *args: Var | Any) -> FunctionVar: ... - def partial(self, *args: Var | Any) -> FunctionVar: # pyright: ignore [reportInconsistentOverload] + def partial(self, *args: Var | Any) -> FunctionVar: """Partially apply the function with the given arguments. Args: @@ -250,7 +250,7 @@ def call( @overload def call(self, *args: Var | Any) -> Var: ... - def call(self, *args: Var | Any) -> Var: # pyright: ignore [reportInconsistentOverload] + def call(self, *args: Var | Any) -> Var: """Call the function with the given arguments. Args: @@ -279,7 +279,7 @@ class FunctionStringVar(FunctionVar[CALLABLE_TYPE]): def create( cls, func: str, - _var_type: type[OTHER_CALLABLE_TYPE] = ReflexCallable[Any, Any], + _var_type: type[OTHER_CALLABLE_TYPE] = ReflexCallable[Any, Any], # ty:ignore[invalid-parameter-default] _var_data: VarData | None = None, ) -> FunctionStringVar[OTHER_CALLABLE_TYPE]: """Create a new function var from a string. diff --git a/packages/reflex-base/src/reflex_base/vars/number.py b/packages/reflex-base/src/reflex_base/vars/number.py index ae3f8ac4987..cc1ee6f3f18 100644 --- a/packages/reflex-base/src/reflex_base/vars/number.py +++ b/packages/reflex-base/src/reflex_base/vars/number.py @@ -294,7 +294,7 @@ def __neg__(self) -> NumberVar: Returns: The number negation operation. """ - return number_negate_operation(self) # pyright: ignore [reportReturnType] + return number_negate_operation(self) def __invert__(self): """Boolean NOT the number. @@ -523,7 +523,7 @@ def wrapper(lhs: number_types, rhs: number_types) -> NumberVar: Returns: The binary number operation. """ - return operation(lhs, rhs) # pyright: ignore [reportReturnType, reportArgumentType] + return operation(lhs, rhs) return wrapper @@ -1137,7 +1137,7 @@ def ternary_operation( Returns: The ternary operation. """ - type_value: type[T] | type[U] = unionize(if_true._var_type, if_false._var_type) + type_value: type[T] | type[U] = unionize(if_true._var_type, if_false._var_type) # ty:ignore[invalid-assignment] value: CustomVarOperationReturn[T | U] = var_operation_return( js_expression=f"({condition} ? {if_true} : {if_false})", var_type=type_value, diff --git a/packages/reflex-base/src/reflex_base/vars/object.py b/packages/reflex-base/src/reflex_base/vars/object.py index 307240f7186..a3d61d84533 100644 --- a/packages/reflex-base/src/reflex_base/vars/object.py +++ b/packages/reflex-base/src/reflex_base/vars/object.py @@ -170,7 +170,7 @@ def merge(self, other: ObjectVar): # NoReturn is used here to catch when key value is Any @overload - def __getitem__( # pyright: ignore [reportOverlappingOverload] + def __getitem__( self: ObjectVar[Mapping[Any, NoReturn]], key: Var | Any, ) -> Var: ... @@ -255,9 +255,9 @@ def get(self, key: Var | Any, default: Var | Any | None = None) -> Var: if default is None: default = Var.create(None) - value = self.__getitem__(key) # pyright: ignore[reportUnknownVariableType,reportAttributeAccessIssue,reportUnknownMemberType] + value = self.__getitem__(key) # ty:ignore[no-matching-overload] - return cond( # pyright: ignore[reportUnknownVariableType] + return cond( value, value, default, @@ -265,7 +265,7 @@ def get(self, key: Var | Any, default: Var | Any | None = None) -> Var: # NoReturn is used here to catch when key value is Any @overload - def __getattr__( # pyright: ignore [reportOverlappingOverload] + def __getattr__( self: ObjectVar[Mapping[Any, NoReturn]], name: str, ) -> Var: ... @@ -384,7 +384,7 @@ def _key_type(self) -> type: The type of the keys of the object. """ args_list = typing.get_args(self._var_type) - return args_list[0] if args_list else Any # pyright: ignore [reportReturnType] + return args_list[0] if args_list else Any def _value_type(self) -> type: """Get the type of the values of the object. @@ -393,7 +393,7 @@ def _value_type(self) -> type: The type of the values of the object. """ args_list = typing.get_args(self._var_type) - return args_list[1] if args_list else Any # pyright: ignore [reportReturnType] + return args_list[1] if args_list else Any @cached_property_no_lock def _cached_var_name(self) -> str: @@ -542,7 +542,7 @@ def object_values_operation(value: ObjectVar): """ return var_operation_return( js_expression=f"Object.values({value} ?? {{}})", - var_type=list[value._value_type()], + var_type=list[value._value_type()], # ty:ignore[invalid-type-form] ) @@ -558,7 +558,7 @@ def object_entries_operation(value: ObjectVar): """ return var_operation_return( js_expression=f"Object.entries({value} ?? {{}})", - var_type=list[tuple[str, value._value_type()]], + var_type=list[tuple[str, value._value_type()]], # ty:ignore[invalid-type-form] ) @@ -576,8 +576,8 @@ def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar): return var_operation_return( js_expression=f"({{...{lhs}, ...{rhs}}})", var_type=Mapping[ - lhs._key_type() | rhs._key_type(), - lhs._value_type() | rhs._value_type(), + lhs._key_type() | rhs._key_type(), # ty:ignore[invalid-type-form] + lhs._value_type() | rhs._value_type(), # ty:ignore[invalid-type-form] ], ) diff --git a/packages/reflex-base/src/reflex_base/vars/sequence.py b/packages/reflex-base/src/reflex_base/vars/sequence.py index a296f0052b8..0f4db6f0a6d 100644 --- a/packages/reflex-base/src/reflex_base/vars/sequence.py +++ b/packages/reflex-base/src/reflex_base/vars/sequence.py @@ -100,7 +100,7 @@ def reverse(self) -> ArrayVar[ARRAY_VAR_TYPE]: Returns: The reversed array. """ - return array_reverse_operation(self) + return array_reverse_operation(self) # ty:ignore[invalid-return-type] def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: """Concatenate two arrays. @@ -114,7 +114,7 @@ def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: if not isinstance(other, ArrayVar): raise_unsupported_operand_types("+", (type(self), type(other))) - return array_concat_operation(self, other) + return array_concat_operation(self, other) # ty:ignore[invalid-return-type] @overload def __getitem__(self, i: slice) -> ArrayVar[ARRAY_VAR_TYPE]: ... @@ -145,7 +145,7 @@ def __getitem__( ) -> NumberVar: ... @overload - def __getitem__( # pyright: ignore [reportOverlappingOverload] + def __getitem__( self: ArrayVar[tuple[str, Any]], i: Literal[0, -2] ) -> StringVar: ... @@ -317,7 +317,7 @@ def pluck(self, field: StringVar | str) -> ArrayVar: Returns: The array pluck operation. """ - return array_pluck_operation(self, field) + return array_pluck_operation(self, field) # ty:ignore[invalid-return-type] def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: """Multiply the sequence by a number or integer. @@ -333,7 +333,7 @@ def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: ): raise_unsupported_operand_types("*", (type(self), type(other))) - return repeat_array_operation(self, other) + return repeat_array_operation(self, other) # ty:ignore[invalid-return-type] __rmul__ = __mul__ @@ -830,7 +830,7 @@ def __ge__(self, other: StringVar | str) -> BooleanVar: return string_ge_operation(self, other) @overload - def replace( # pyright: ignore [reportOverlappingOverload] + def replace( self, search_value: StringVar | str, new_value: StringVar | str ) -> StringVar: ... @@ -839,7 +839,7 @@ def replace( self, search_value: Any, new_value: Any ) -> CustomVarOperationReturn[StringVar]: ... - def replace(self, search_value: Any, new_value: Any) -> StringVar: # pyright: ignore [reportInconsistentOverload] + def replace(self, search_value: Any, new_value: Any) -> StringVar: """Replace a string with a value. Args: diff --git a/packages/reflex-components-code/src/reflex_components_code/shiki_code_block.py b/packages/reflex-components-code/src/reflex_components_code/shiki_code_block.py index f18568d5912..1a2149684ef 100644 --- a/packages/reflex-components-code/src/reflex_components_code/shiki_code_block.py +++ b/packages/reflex-components-code/src/reflex_components_code/shiki_code_block.py @@ -613,7 +613,7 @@ def create( transformer_styles = {} # Collect styles from transformers and wrapper - for transformer in code_block.transformers._var_value: # pyright: ignore [reportAttributeAccessIssue] + for transformer in code_block.transformers._var_value: # ty:ignore[unresolved-attribute] if isinstance(transformer, ShikiBaseTransformers) and transformer.style: transformer_styles.update(transformer.style) transformer_styles.update(code_wrapper_props.pop("style", {})) @@ -668,7 +668,7 @@ def create_transformer(cls, library: str, fns: list[str]) -> ShikiBaseTransforme raise ValueError(msg) return ShikiBaseTransformers( library=library, - fns=[FunctionStringVar.create(fn) for fn in fns], # pyright: ignore [reportCallIssue] + fns=[FunctionStringVar.create(fn) for fn in fns], ) def _render(self, props: dict[str, Any] | None = None): diff --git a/packages/reflex-components-core/src/reflex_components_core/core/banner.py b/packages/reflex-components-core/src/reflex_components_core/core/banner.py index 8d9af0bef76..5272fb8c4e9 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/banner.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/banner.py @@ -102,7 +102,7 @@ def add_hooks(self) -> list[str | Var]: close_button=True, duration=120000, id=toast_id, - ) # pyright: ignore [reportCallIssue] + ) if environment.REFLEX_DOES_BACKEND_COLD_START.get(): loading_message = Var.create("Backend is starting.") diff --git a/packages/reflex-components-core/src/reflex_components_core/core/breakpoints.py b/packages/reflex-components-core/src/reflex_components_core/core/breakpoints.py index e6277d6327d..1d406a2f916 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/breakpoints.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/breakpoints.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.breakpoints import * # pragma: no cover diff --git a/packages/reflex-components-core/src/reflex_components_core/core/cond.py b/packages/reflex-components-core/src/reflex_components_core/core/cond.py index a35443cb17c..53cd58866fa 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/cond.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/cond.py @@ -118,7 +118,7 @@ def add_imports(self) -> ImportDict: @overload -def cond(condition: Any, c1: Component, c2: Any, /) -> Component: ... # pyright: ignore [reportOverlappingOverload] +def cond(condition: Any, c1: Component, c2: Any, /) -> Component: ... @overload @@ -126,7 +126,7 @@ def cond(condition: Any, c1: Component, /) -> Component: ... @overload -def cond(condition: Any, c1: Any, c2: Component, /) -> Component: ... # pyright: ignore [reportOverlappingOverload] +def cond(condition: Any, c1: Any, c2: Component, /) -> Component: ... T = TypeVar("T", covariant=True) @@ -134,15 +134,15 @@ def cond(condition: Any, c1: Any, c2: Component, /) -> Component: ... # pyright @overload -def cond(condition: Any, c1: Var[T], c2: Var[U], /) -> Var[T | U]: ... # pyright: ignore [reportOverlappingOverload] +def cond(condition: Any, c1: Var[T], c2: Var[U], /) -> Var[T | U]: ... @overload -def cond(condition: Any, c1: T, c2: Var[U], /) -> Var[T | U]: ... # pyright: ignore [reportOverlappingOverload] +def cond(condition: Any, c1: T, c2: Var[U], /) -> Var[T | U]: ... @overload -def cond(condition: Any, c1: Var[T], c2: U, /) -> Var[T | U]: ... # pyright: ignore [reportOverlappingOverload] +def cond(condition: Any, c1: Var[T], c2: U, /) -> Var[T | U]: ... @overload @@ -199,7 +199,7 @@ def cond(condition: Any, c1: Any, c2: Any = types.Unset(), /) -> Component | Var @overload -def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # pyright: ignore [reportOverlappingOverload] +def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... @overload diff --git a/packages/reflex-components-core/src/reflex_components_core/core/debounce.py b/packages/reflex-components-core/src/reflex_components_core/core/debounce.py index b627e87eea5..42e7156f698 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/debounce.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/debounce.py @@ -142,12 +142,12 @@ def create(cls, *children: Component, **props: Any) -> Component: ) component = super().create(**props) - component._get_style = child._get_style + component._get_style = child._get_style # ty:ignore[invalid-assignment] component.event_triggers.update(child.event_triggers) component.children = child.children - component._rename_props = child._rename_props # pyright: ignore[reportAttributeAccessIssue] + component._rename_props = child._rename_props # ty:ignore[invalid-attribute-access] outer_get_all_custom_code = component._get_all_custom_code - component._get_all_custom_code = lambda: ( + component._get_all_custom_code = lambda: ( # ty:ignore[invalid-assignment] outer_get_all_custom_code() | (child._get_all_custom_code()) ) return component diff --git a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py index 1df59feda9d..7eee3be664c 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/foreach.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/foreach.py @@ -122,7 +122,7 @@ def create( return component def _render(self) -> IterTag: - props = {} + props: dict[str, Any] = {} render_sig = inspect.signature(self.render_fn) params = list(render_sig.parameters.values()) @@ -149,7 +149,7 @@ def _render(self) -> IterTag: if (render_fn_code := getattr(render_fn, "__code__", None)) is not None: code_hash = md5(render_fn_code.co_code).hexdigest() elif isinstance(render_fn, functools.partial): - code_hash = md5(render_fn.func.__code__.co_code).hexdigest() + code_hash = md5(render_fn.func.__code__.co_code).hexdigest() # ty:ignore[unresolved-attribute] else: code_hash = md5(repr(render_fn).encode()).hexdigest() props["index_var_name"] = f"index_{code_hash}" diff --git a/packages/reflex-components-core/src/reflex_components_core/core/match.py b/packages/reflex-components-core/src/reflex_components_core/core/match.py index 9216cfb767b..b45709b9fff 100644 --- a/packages/reflex-components-core/src/reflex_components_core/core/match.py +++ b/packages/reflex-components-core/src/reflex_components_core/core/match.py @@ -197,16 +197,17 @@ def _validate_return_types( MatchTypeError: If the return types of cases are different. """ first_case_return = match_cases[0][-1] - return_type = type(first_case_return) - + return_type: type[Var] | type[BaseComponent] if isinstance(first_case_return, BaseComponent): return_type = BaseComponent elif isinstance(first_case_return, Var): return_type = Var + else: + msg = "Return value must be a var or component" + raise MatchTypeError(msg) - cases = [] for index, case in enumerate(match_cases): - conditions, return_value = case + return_value = case[-1] if not isinstance(return_value, return_type): msg = ( f"Match cases should have the same return types. Case {index} with return " @@ -214,8 +215,7 @@ def _validate_return_types( f" of type {type(return_value)!r} is not {return_type}" ) raise MatchTypeError(msg) - cases.append((conditions, return_value)) - return cases + return match_cases # ty:ignore[invalid-return-type] @classmethod def _create_match_cond_var_or_component( @@ -244,7 +244,7 @@ def _create_match_cond_var_or_component( cond=match_cond_var, match_cases=match_cases, default=default, - children=[case[1] for case in match_cases] + [default], # pyright: ignore [reportArgumentType] + children=[case[1] for case in match_cases] + [default], # ty:ignore[invalid-argument-type] ) ) diff --git a/packages/reflex-components-core/src/reflex_components_core/el/elements/forms.py b/packages/reflex-components-core/src/reflex_components_core/el/elements/forms.py index beed14826ac..c44d82ebc30 100644 --- a/packages/reflex-components-core/src/reflex_components_core/el/elements/forms.py +++ b/packages/reflex-components-core/src/reflex_components_core/el/elements/forms.py @@ -196,7 +196,7 @@ def create(cls, *children, **props): # Render the form hooks and use the hash of the resulting code to create a unique name. props["handle_submit_unique_name"] = "" form = super().create(*children, **props) - form.handle_submit_unique_name = md5( # pyright: ignore[reportAttributeAccessIssue] + form.handle_submit_unique_name = md5( # ty:ignore[unresolved-attribute] str(form._get_all_hooks()).encode("utf-8") ).hexdigest() return form diff --git a/packages/reflex-components-internal/src/reflex_components_internal/components/base/__init__.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/__init__.py index a1097feeba0..a8d118dd3d2 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/__init__.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/__init__.py @@ -11,5 +11,5 @@ __getattr__, __dir__, __all__ = lazy_loader.attach( __name__, submodules=_SUBMODULES, - submod_attrs=_SUBMOD_ATTRS, + submod_attrs=_SUBMOD_ATTRS, # ty:ignore[invalid-argument-type] ) diff --git a/packages/reflex-components-internal/src/reflex_components_internal/components/base/checkbox.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/checkbox.py index 4e5a135af9c..3d8d8880913 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/checkbox.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/checkbox.py @@ -123,7 +123,7 @@ def create(cls, *children, **props) -> BaseUIComponent: """ class_name = props.pop("class_name", "") if label := props.pop("label", None): - return Label.create( # pyright: ignore[reportReturnType] + return Label.create( CheckboxRoot.create( CheckboxIndicator.create(), *children, @@ -131,7 +131,7 @@ def create(cls, *children, **props) -> BaseUIComponent: ), label, class_name=cn(ClassNames.LABEL, class_name), - ) + ) # ty:ignore[invalid-return-type] return CheckboxRoot.create( CheckboxIndicator.create(), *children, diff --git a/packages/reflex-components-internal/src/reflex_components_internal/components/base/input.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/input.py index 824836ea4af..f349a3476e5 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/input.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/input.py @@ -59,7 +59,7 @@ class InputRoot(InputBaseComponent, ReflexInput): render_: Var[Component] @classmethod - def create(cls, *children, **props) -> "InputRoot": # pyright: ignore[reportIncompatibleMethodOverride] + def create(cls, *children, **props) -> "InputRoot": """Create a high level input component with simplified API. Returns: @@ -67,7 +67,7 @@ def create(cls, *children, **props) -> "InputRoot": # pyright: ignore[reportInc """ props["data-slot"] = "input" cls.set_class_name(ClassNames.INPUT, props) - return super().create(*children, **props) # pyright: ignore[reportReturnType] + return super().create(*children, **props) # ty:ignore[invalid-return-type] class HighLevelInput(InputBaseComponent): @@ -151,7 +151,7 @@ def create(cls, *children, **props) -> BaseUIComponent: }, }) - return Div.create( # pyright: ignore[reportReturnType] + return Div.create( ( Span.create( hi(icon, class_name="text-secondary-12 size-4 pointer-events-none"), @@ -166,7 +166,7 @@ def create(cls, *children, **props) -> BaseUIComponent: on_click=set_focus(id), class_name=cn(f"{ClassNames.DIV} {INPUT_SIZE_VARIANTS[size]}", class_name), **props, - ) + ) # ty:ignore[invalid-return-type] @staticmethod def _create_clear_button(id: str, clear_events: list[EventHandler]) -> Button: diff --git a/packages/reflex-components-radix/src/reflex_components_radix/themes/components/icon_button.py b/packages/reflex-components-radix/src/reflex_components_radix/themes/components/icon_button.py index d0e089e9041..508d67380e4 100644 --- a/packages/reflex-components-radix/src/reflex_components_radix/themes/components/icon_button.py +++ b/packages/reflex-components-radix/src/reflex_components_radix/themes/components/icon_button.py @@ -76,7 +76,7 @@ def create(cls, *children, **props) -> Component: raise ValueError(msg) if "size" in props: if isinstance(props["size"], str): - children[0].size = RADIX_TO_LUCIDE_SIZE[props["size"]] # pyright: ignore[reportAttributeAccessIssue] + children[0].size = RADIX_TO_LUCIDE_SIZE[props["size"]] # ty:ignore[invalid-assignment] else: size_map_var = Match.create( props["size"], @@ -86,7 +86,7 @@ def create(cls, *children, **props) -> Component: if not isinstance(size_map_var, Var): msg = f"Match did not return a Var: {size_map_var}" raise ValueError(msg) - children[0].size = size_map_var # pyright: ignore[reportAttributeAccessIssue] + children[0].size = size_map_var # ty:ignore[invalid-assignment] return super().create(*children, **props) def add_style(self): diff --git a/packages/reflex-components-radix/src/reflex_components_radix/themes/layout/list.py b/packages/reflex-components-radix/src/reflex_components_radix/themes/layout/list.py index 9ba8e1e747c..d0e3925912e 100644 --- a/packages/reflex-components-radix/src/reflex_components_radix/themes/layout/list.py +++ b/packages/reflex-components-radix/src/reflex_components_radix/themes/layout/list.py @@ -174,7 +174,7 @@ def create(cls, *children, **props): for child in children: if isinstance(child, Text): - child.as_ = "span" # pyright: ignore[reportAttributeAccessIssue] + child.as_ = "span" elif isinstance(child, Icon) and "display" not in child.style: child.style["display"] = "inline" return super().create(*children, **props) diff --git a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py index f08457b526d..c383e2efe14 100644 --- a/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py +++ b/packages/reflex-components-sonner/src/reflex_components_sonner/toast.py @@ -2,6 +2,7 @@ from __future__ import annotations +import builtins import dataclasses from typing import Any, Literal @@ -137,7 +138,7 @@ class ToastProps(NoExtrasAllowedProps): # Function that gets called when the toast disappears automatically after it's timeout (duration` prop). on_auto_close: Any | None - def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: + def dict(self, *args: Any, **kwargs: Any) -> builtins.dict[str, Any]: """Convert the object to a dictionary. Args: @@ -152,11 +153,11 @@ def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: if "action" in d: d["action"] = self.action if isinstance(self.action, dict): - d["action"] = ToastAction(**self.action) + d["action"] = ToastAction(**self.action) # ty:ignore[invalid-argument-type] if "cancel" in d: d["cancel"] = self.cancel if isinstance(self.cancel, dict): - d["cancel"] = ToastAction(**self.cancel) + d["cancel"] = ToastAction(**self.cancel) # ty:ignore[invalid-argument-type] if "onDismiss" in d: d["onDismiss"] = format.format_queue_events( self.on_dismiss, _toast_callback_signature @@ -271,7 +272,7 @@ def send_toast( raise ValueError(msg) if props: - args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # pyright: ignore [reportCallIssue] + args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # ty:ignore[unknown-argument] toast = toast_command.call(message, args) else: toast = toast_command.call(message) diff --git a/packages/reflex-docgen/src/reflex_docgen/markdown/_parser.py b/packages/reflex-docgen/src/reflex_docgen/markdown/_parser.py index d9f1a782ced..99de7e9b099 100644 --- a/packages/reflex-docgen/src/reflex_docgen/markdown/_parser.py +++ b/packages/reflex-docgen/src/reflex_docgen/markdown/_parser.py @@ -273,9 +273,9 @@ def _convert_block(token: BlockToken) -> Block | None: raise TypeError(msg) item_blocks = _convert_block_children(item_token) items.append(ListItem(children=item_blocks)) - # List.start is an instance attribute (int | None) but pyright sees + # List.start is an instance attribute (int | None) but the type checker sees # the classmethod start(cls, line) instead. - list_start = cast("int | None", token.start) # pyright: ignore[reportAttributeAccessIssue] + list_start = cast("int | None", token.start) return ListBlock( ordered=list_start is not None, start=list_start, diff --git a/packages/reflex-hosting-cli/src/reflex_cli/deployments.py b/packages/reflex-hosting-cli/src/reflex_cli/deployments.py index 665d417592e..4b29b96bb38 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/deployments.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/deployments.py @@ -229,7 +229,7 @@ def get_group_from_info(group_info: TyperInfo, *args, **kwargs): original_get_group_from_info, ) - typer.main.get_group_from_info = get_group_from_info + typer.main.get_group_from_info = get_group_from_info # ty:ignore[invalid-assignment] return fake_typer_app @@ -239,4 +239,4 @@ def get_group_from_info(group_info: TyperInfo, *args, **kwargs): and find_spec("typer.core") is not None and find_spec("typer.models") is not None ): - deployments_cli = _patch_typer(deployments_cli) # pyright: ignore[reportAssignmentType] + deployments_cli = _patch_typer(deployments_cli) # ty:ignore[invalid-assignment] diff --git a/packages/reflex-hosting-cli/src/reflex_cli/utils/hosting.py b/packages/reflex-hosting-cli/src/reflex_cli/utils/hosting.py index ef8db9f4ba1..f274fcc53a8 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/utils/hosting.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/utils/hosting.py @@ -123,13 +123,13 @@ def create( """ if isinstance(regions, list): - regions = dict.fromkeys(regions, 1) + regions = dict.fromkeys(regions, 1) # ty:ignore[invalid-assignment] return cls( scale_type, vm_type, tuple( Region(name=name, number_of_machines=number) - for name, number in regions.items() + for name, number in regions.items() # ty:ignore[unresolved-attribute] ) if regions else (), @@ -339,7 +339,7 @@ def open(self, url: str, new: int = 0, autoraise: bool = True): return False -webbrowser.BackgroundBrowser = SilentBackgroundBrowser +webbrowser.BackgroundBrowser = SilentBackgroundBrowser # ty:ignore[invalid-assignment] def get_existing_access_token() -> str: diff --git a/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py b/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py index 4ae50f52eb4..b6cf6c8a201 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py @@ -365,7 +365,7 @@ def deploy( if envfile: try: - from dotenv import dotenv_values # pyright: ignore[reportMissingImports] + from dotenv import dotenv_values processed_envs = dotenv_values(envfile) except ImportError: @@ -393,7 +393,7 @@ def deploy( False, True, True, - ) # pyright: ignore[reportCallIssue] + ) # ty:ignore[missing-argument] else: export_fn( str(temporary_dir_path), @@ -402,7 +402,7 @@ def deploy( False, True, include_db, - True, # pyright: ignore[reportCallIssue] + True, # ty:ignore[too-many-positional-arguments] ) except Exception as ex: console.error(f"Unable to export due to: {ex}") @@ -414,7 +414,7 @@ def deploy( try: # Check if the reflex version is >= 0.7.6 if rx_version <= breaking_version: - export_fn(str(temporary_dir_path), server_url, host_url, True, False, True) # pyright: ignore[reportCallIssue] + export_fn(str(temporary_dir_path), server_url, host_url, True, False, True) # ty:ignore[missing-argument] else: export_fn( str(temporary_dir_path), @@ -423,7 +423,7 @@ def deploy( True, False, include_db, - True, # pyright: ignore[reportCallIssue] + True, # ty:ignore[too-many-positional-arguments] ) except ImportError as ie: console.error( diff --git a/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py b/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py index 37c680fd7ca..388583687f2 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py @@ -97,7 +97,7 @@ def get_group_from_info(group_info: TyperInfo, *args, **kwargs): original_get_group_from_info, ) - typer.main.get_group_from_info = get_group_from_info + typer.main.get_group_from_info = get_group_from_info # ty:ignore[invalid-assignment] return fake_typer_app @@ -107,7 +107,7 @@ def get_group_from_info(group_info: TyperInfo, *args, **kwargs): and find_spec("typer.core") is not None and find_spec("typer.models") is not None ): - hosting_cli = _patch_typer(hosting_cli) # pyright: ignore[reportAssignmentType] + hosting_cli = _patch_typer(hosting_cli) # ty:ignore[invalid-assignment] TIME_FORMAT_HELP = "Accepts ISO 8601 format, unix epoch or time relative to now. For time relative to now, use the format: . Valid units are d (day), h (hour), m (minute), s (second). For example, 1d for 1 day ago from now." MIN_LOGS_LIMIT = 50 diff --git a/packages/reflex-hosting-cli/src/reflex_cli/v2/secrets.py b/packages/reflex-hosting-cli/src/reflex_cli/v2/secrets.py index 3f1b28f66a6..4ad17f8741f 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/v2/secrets.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/v2/secrets.py @@ -158,9 +158,7 @@ def update_secrets( if envfile: try: - from dotenv import ( # pyright: ignore[reportMissingImports] - dotenv_values, - ) + from dotenv import dotenv_values except ImportError: console.error( """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`.""" diff --git a/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/flexdown.py b/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/flexdown.py index 5b52091bf83..a35d4896022 100644 --- a/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/flexdown.py +++ b/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/flexdown.py @@ -1,6 +1,5 @@ """Flexdown module — component maps and markdown helpers.""" -# pyright: reportAttributeAccessIssue=false from reflex_base.constants.colors import ColorType from reflex_components_code.shiki_code_block import code_block as shiki_code_block diff --git a/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/headings.py b/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/headings.py index 4a0808f6613..ec1abdc49fd 100644 --- a/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/headings.py +++ b/packages/reflex-site-shared/src/reflex_site_shared/components/blocks/headings.py @@ -1,4 +1,3 @@ -# pyright: reportArgumentType=false, reportReturnType=false, reportOperatorIssue=false """Template for documentation pages.""" from typing import ClassVar diff --git a/pyi_hashes.json b/pyi_hashes.json index 00ea0719dfd..2b89b363ea6 100644 --- a/pyi_hashes.json +++ b/pyi_hashes.json @@ -117,8 +117,8 @@ "packages/reflex-components-recharts/src/reflex_components_recharts/general.pyi": "5a1a479924ad6184abafe4d796cb04c5", "packages/reflex-components-recharts/src/reflex_components_recharts/polar.pyi": "1979bb6c22bb7a0d3342b2d63fb19d74", "packages/reflex-components-recharts/src/reflex_components_recharts/recharts.pyi": "c5288f311fe37b23539518ba2a3d4482", - "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "2c5fadcc014056f041cd4d916137d9e7", + "packages/reflex-components-sonner/src/reflex_components_sonner/toast.pyi": "ba6c853c503fd8ad6fe89350ef4df073", "reflex/__init__.pyi": "3a9bb8544cbc338ffaf0a5927d9156df", "reflex/components/__init__.pyi": "f39a2af77f438fa243c58c965f19d42e", - "reflex/experimental/memo.pyi": "d09629b81bf0df6153b131ac0ee10bd7" + "reflex/experimental/memo.pyi": "067c8e83dbcd9daf9baea51396d91cae" } diff --git a/pyproject.toml b/pyproject.toml index 14236daf7c5..4d083b7a0a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,7 +93,6 @@ dev = [ "psutil", "psycopg[binary]", "pydantic", - "pyright", "pytest-asyncio", "pytest-benchmark", "pytest-codspeed", @@ -111,6 +110,7 @@ dev = [ "sqlmodel", "starlette-admin", "toml", + "ty", "typer", "uvicorn", ] @@ -136,25 +136,13 @@ path = "scripts/hatch_build.py" dependencies = ["plotly", "ruff"] require-runtime-dependencies = true -[tool.pyright] -extraPaths = [ - "packages/reflex-code/src", - "packages/reflex-components/src", - "packages/reflex-dataeditor/src", - "packages/reflex-gridjs/src", - "packages/reflex-lucide/src", - "packages/reflex-markdown/src", - "packages/reflex-moment/src", - "packages/reflex-plotly/src", - "packages/reflex-radix/src", - "packages/reflex-react-player/src", - "packages/reflex-react-router/src", - "packages/reflex-recharts/src", - "packages/reflex-sonner/src", - "packages/reflex-components-internal/src", - "packages/reflex-site-shared/src", - "packages/integrations-docs/src", -] +[tool.ty.environment] +# Type-check against Python 3.11 stdlib so newer-Python-only features like +# `dis.Positions`, `tomllib`, and `ExceptionGroup` resolve. Reflex still +# supports Python 3.10 at runtime via `sys.version_info >= (3, 11)` guards. +python-version = "3.11" + +[tool.ty.src] exclude = [ ".venv", "**/__pycache__", @@ -164,9 +152,11 @@ exclude = [ "docs", "packages/reflex-site-shared", "packages/integrations-docs", - "packages/reflex-ui-shared", ] -reportIncompatibleMethodOverride = false + +[tool.ty.rules] +invalid-method-override = "ignore" +unsupported-base = "ignore" [tool.ruff] target-version = "py310" diff --git a/reflex/_upload.py b/reflex/_upload.py index b8b2dcfe48f..96c43b34020 100644 --- a/reflex/_upload.py +++ b/reflex/_upload.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_components_core.core._upload.""" from reflex_components_core.core._upload import * # pragma: no cover diff --git a/reflex/app.py b/reflex/app.py index 91a8180e262..d0c3fe60a2b 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -695,7 +695,7 @@ def __call__(self) -> ASGIApp: [self.api_transformer] if not isinstance(self.api_transformer, Sequence) else self.api_transformer - ) + ) # ty:ignore[invalid-assignment] for api_transformer in api_transformers: if isinstance(api_transformer, Starlette): @@ -850,7 +850,9 @@ def add_page( msg = "Route must be set if component is not a callable." raise exceptions.RouteValueError(msg) # Format the route. - route = format.format_route(format.to_kebab_case(component.__name__)) + route = format.format_route( + format.to_kebab_case(format.callable_name(component)) + ) else: route = format.format_route(route) @@ -1300,7 +1302,7 @@ def modify_state( previous_dirty_vars: dict[str, set[str]] | None = None, ) -> contextlib.AbstractAsyncContextManager[BaseState]: ... - @contextlib.asynccontextmanager + @contextlib.asynccontextmanager # ty:ignore[no-matching-overload] async def modify_state( self, token: BaseStateToken | str, @@ -1462,7 +1464,7 @@ async def health(_request: Request) -> JSONResponse: - "db" (bool or str): Database status - True, False, or "NA". - "redis" (bool or str): Redis status - True, False, or "NA". """ - health_status = {"status": True} + health_status: dict[str, bool | None] = {"status": True} status_code = 200 tasks = [] diff --git a/reflex/app_mixins/lifespan.py b/reflex/app_mixins/lifespan.py index 692862bcb8e..3108650b1e5 100644 --- a/reflex/app_mixins/lifespan.py +++ b/reflex/app_mixins/lifespan.py @@ -13,6 +13,7 @@ from reflex_base.utils import console from reflex_base.utils.exceptions import InvalidLifespanTaskTypeError +from reflex_base.utils.format import callable_name from starlette.applications import Starlette from .mixin import AppMixin @@ -34,7 +35,7 @@ def _get_task_name(task: asyncio.Task | Callable) -> str: """ if isinstance(task, asyncio.Task): return task.get_name() - return task.__name__ # pyright: ignore[reportAttributeAccessIssue] + return callable_name(task) @dataclasses.dataclass @@ -123,22 +124,18 @@ async def _run_lifespan_tasks(self, starlette_app: Starlette): console.debug(f"Canceling lifespan task: {task}") task.cancel(msg="lifespan_cleanup") # Disassociate sid / token pairings so they can be reconnected properly. - try: - event_namespace = self.event_namespace # pyright: ignore[reportAttributeAccessIssue] - except AttributeError: - pass - else: + event_namespace = getattr(self, "event_namespace", None) + if event_namespace: try: - if event_namespace: - await event_namespace._token_manager.disconnect_all() + await event_namespace._token_manager.disconnect_all() except Exception as e: console.error(f"Error during lifespan cleanup: {e}") # Flush any pending writes from the state manager. try: - state_manager = self.state_manager # pyright: ignore[reportAttributeAccessIssue] - except (AttributeError, ValueError): - pass - else: + state_manager = getattr(self, "state_manager", None) + except ValueError: + state_manager = None + if state_manager is not None: await state_manager.close() @overload @@ -185,7 +182,7 @@ def register_lifespan_task( ) raise RuntimeError(msg) if inspect.isgeneratorfunction(task) or inspect.isasyncgenfunction(task): - msg = f"Task {task.__name__} of type generator must be decorated with contextlib.asynccontextmanager." + msg = f"Task {_get_task_name(task)} of type generator must be decorated with contextlib.asynccontextmanager." raise InvalidLifespanTaskTypeError(msg) task_name = _get_task_name(task) diff --git a/reflex/app_mixins/middleware.py b/reflex/app_mixins/middleware.py index c9bea19e922..f9c5f4fe451 100644 --- a/reflex/app_mixins/middleware.py +++ b/reflex/app_mixins/middleware.py @@ -49,7 +49,7 @@ async def _preprocess(self, state: BaseState, event: Event) -> StateUpdate | Non An optional state to return. """ for middleware in self._middlewares: - out = middleware.preprocess(app=self, state=state, event=event) # pyright: ignore [reportArgumentType] + out = middleware.preprocess(app=self, state=state, event=event) # ty:ignore[invalid-argument-type] if inspect.isawaitable(out): out = await out if out is not None: @@ -75,11 +75,11 @@ async def _postprocess( out = update for middleware in self._middlewares: out = middleware.postprocess( - app=self, # pyright: ignore [reportArgumentType] + app=self, # ty:ignore[invalid-argument-type] state=state, event=event, update=update, ) if inspect.isawaitable(out): out = await out - return out # pyright: ignore[reportReturnType] + return out diff --git a/reflex/assets.py b/reflex/assets.py index 06e4e739b9a..522b16ed3d2 100644 --- a/reflex/assets.py +++ b/reflex/assets.py @@ -65,7 +65,7 @@ def __new__( else: relative_path = str.__new__( str, - object, # pyright: ignore[reportArgumentType] + object, # ty:ignore[invalid-argument-type] "utf-8" if encoding is None else encoding, "strict" if errors is None else errors, ) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index a0a934c1b6d..3ff22f4071f 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -25,7 +25,7 @@ from reflex_base.plugins import CompileContext, CompilerHooks, PageContext, Plugin from reflex_base.style import SYSTEM_COLOR_MODE from reflex_base.utils.exceptions import ReflexError -from reflex_base.utils.format import to_title_case +from reflex_base.utils.format import callable_name, to_title_case from reflex_base.utils.imports import ImportVar from reflex_base.vars.base import LiteralVar, Var from reflex_components_core.base.app_wrap import AppWrap @@ -760,9 +760,10 @@ def readable_name_from_component( module = getmodule(component) if module is not None: module_name = module.__name__ + name = callable_name(component) if module_name is not None: - return f"{module_name}.{component.__name__}" - return component.__name__ + return f"{module_name}.{name}" + return name return None @@ -813,7 +814,7 @@ def into_component(component: Component | ComponentCallable) -> Component: raise TypeError(msg) try: - component_called = component() + component_called = component() # ty:ignore[call-top-callable] except KeyError as e: if isinstance(e, ReflexError): _modify_exception(e) @@ -891,23 +892,17 @@ def compile_unevaluated_page( component = Fragment.create(component) - meta_args = { - "title": ( + # Add meta information to the component. + utils.add_meta( + component, + title=( page.title if page.title is not None else make_default_page_title(get_config().app_name, route) ), - "image": page.image, - "meta": page.meta, - } - - if page.description is not None: - meta_args["description"] = page.description - - # Add meta information to the component. - utils.add_meta( - component, - **meta_args, + image=page.image, + meta=page.meta, + description=page.description, ) except Exception as e: diff --git a/reflex/compiler/plugins/builtin.py b/reflex/compiler/plugins/builtin.py index a4b326be4ab..bf00c3ce5cc 100644 --- a/reflex/compiler/plugins/builtin.py +++ b/reflex/compiler/plugins/builtin.py @@ -54,7 +54,7 @@ def eval_page( if (description := getattr(page, "description", None)) is not None: meta_args["description"] = description - utils.add_meta(component, **meta_args) + utils.add_meta(component, **meta_args) # ty:ignore[invalid-argument-type] except Exception as err: if hasattr(err, "add_note"): err.add_note(f"Happened while evaluating page {page.route!r}") diff --git a/reflex/compiler/templates.py b/reflex/compiler/templates.py index 7ac0223331d..486858ed475 100644 --- a/reflex/compiler/templates.py +++ b/reflex/compiler/templates.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.compiler.templates import * # pragma: no cover diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index ca1cf146d11..87e9b107d11 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -223,7 +223,7 @@ def compile_state(state: type[BaseState]) -> dict: resolved_initial_state = pool.submit( asyncio.run, _resolve_delta(initial_state) ).result() - return _sorted_keys(resolved_initial_state) + return _sorted_keys(resolved_initial_state) # ty:ignore[invalid-argument-type] # Normally the compile runs before any event loop starts, we asyncio.run is available for calling. return _sorted_keys(asyncio.run(_resolve_delta(initial_state))) @@ -613,11 +613,10 @@ def create_document_root( for component in head_components or []: if isinstance(component, Meta): - if component.char_set is not None: # pyright: ignore[reportAttributeAccessIssue] + if component.char_set is not None: # ty:ignore[unresolved-attribute] existing_meta_types.add("char_set") - if ( - (name := component.name) is not None # pyright: ignore[reportAttributeAccessIssue] - and name.equals(Var.create("viewport")) + if (name := component.name) is not None and name.equals( # ty:ignore[unresolved-attribute] + Var.create("viewport") ): existing_meta_types.add("viewport") @@ -814,10 +813,10 @@ def get_memo_components_dir() -> str: def add_meta( page: Component, - title: str, - image: str, + title: str | Var, + image: str | Var, meta: Sequence[Mapping[str, Any] | Component], - description: str | None = None, + description: str | Var | None = None, ) -> Component: """Add metadata to a page. diff --git a/reflex/components/component.py b/reflex/components/component.py index 4affaccc7fe..fddd1f07bee 100644 --- a/reflex/components/component.py +++ b/reflex/components/component.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.component import * # pragma: no cover diff --git a/reflex/components/dynamic.py b/reflex/components/dynamic.py index f2612eb8532..8fd607067a8 100644 --- a/reflex/components/dynamic.py +++ b/reflex/components/dynamic.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.dynamic import * # pragma: no cover diff --git a/reflex/components/field.py b/reflex/components/field.py index 6fe5b1dd916..5c41215c895 100644 --- a/reflex/components/field.py +++ b/reflex/components/field.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.field import * # pragma: no cover diff --git a/reflex/components/literals.py b/reflex/components/literals.py index 0738bda1331..d6a5ee042d5 100644 --- a/reflex/components/literals.py +++ b/reflex/components/literals.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.components.literals.""" from reflex_base.components.literals import * # pragma: no cover diff --git a/reflex/components/props.py b/reflex/components/props.py index 8ea89b2ab1b..b8cdfe7ffc0 100644 --- a/reflex/components/props.py +++ b/reflex/components/props.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.components.props.""" from reflex_base.components.props import * # pragma: no cover diff --git a/reflex/components/tags/__init__.py b/reflex/components/tags/__init__.py index 855786c12bf..e3e1c3fa6c2 100644 --- a/reflex/components/tags/__init__.py +++ b/reflex/components/tags/__init__.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags import * # pragma: no cover diff --git a/reflex/components/tags/cond_tag.py b/reflex/components/tags/cond_tag.py index 5d9a8b0a226..677ddc5d630 100644 --- a/reflex/components/tags/cond_tag.py +++ b/reflex/components/tags/cond_tag.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags.cond_tag import * # pragma: no cover diff --git a/reflex/components/tags/iter_tag.py b/reflex/components/tags/iter_tag.py index 9bb13e2ba03..414d830dd1e 100644 --- a/reflex/components/tags/iter_tag.py +++ b/reflex/components/tags/iter_tag.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags.iter_tag import * # pragma: no cover diff --git a/reflex/components/tags/match_tag.py b/reflex/components/tags/match_tag.py index b3f09d058a3..5995bcd4f84 100644 --- a/reflex/components/tags/match_tag.py +++ b/reflex/components/tags/match_tag.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags.match_tag import * # pragma: no cover diff --git a/reflex/components/tags/tag.py b/reflex/components/tags/tag.py index 95365b678a8..2ae9df9c94b 100644 --- a/reflex/components/tags/tag.py +++ b/reflex/components/tags/tag.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags.tag import * # pragma: no cover diff --git a/reflex/components/tags/tagless.py b/reflex/components/tags/tagless.py index cf0d12ee2ff..3ae0c1c7351 100644 --- a/reflex/components/tags/tagless.py +++ b/reflex/components/tags/tagless.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.components.tags.tagless import * # pragma: no cover diff --git a/reflex/config.py b/reflex/config.py index 1d015fcf056..1054947ad34 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.config.""" from reflex_base.config import * # pragma: no cover diff --git a/reflex/constants/base.py b/reflex/constants/base.py index b500c7e5f0c..f42e8240952 100644 --- a/reflex/constants/base.py +++ b/reflex/constants/base.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.constants.base import * # pragma: no cover diff --git a/reflex/constants/colors.py b/reflex/constants/colors.py index c1f1bf610fe..1b7d9cca3e5 100644 --- a/reflex/constants/colors.py +++ b/reflex/constants/colors.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.constants.colors import * # pragma: no cover diff --git a/reflex/constants/compiler.py b/reflex/constants/compiler.py index e8a4e38a6eb..c99bef62b4a 100644 --- a/reflex/constants/compiler.py +++ b/reflex/constants/compiler.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.constants.compiler import * # pragma: no cover diff --git a/reflex/constants/config.py b/reflex/constants/config.py index 1263c236c93..fca2cac594f 100644 --- a/reflex/constants/config.py +++ b/reflex/constants/config.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.constants.config.""" from reflex_base.constants.config import * # pragma: no cover diff --git a/reflex/constants/custom_components.py b/reflex/constants/custom_components.py index 03a7f79c998..09327836782 100644 --- a/reflex/constants/custom_components.py +++ b/reflex/constants/custom_components.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.constants.custom_components.""" from reflex_base.constants.custom_components import * # pragma: no cover diff --git a/reflex/constants/event.py b/reflex/constants/event.py index 823ac585643..886ea8ef1bc 100644 --- a/reflex/constants/event.py +++ b/reflex/constants/event.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.constants.event import * # pragma: no cover diff --git a/reflex/constants/installer.py b/reflex/constants/installer.py index 54bf46fb30e..e2560af2a80 100644 --- a/reflex/constants/installer.py +++ b/reflex/constants/installer.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.constants.installer.""" from reflex_base.constants.installer import * # pragma: no cover diff --git a/reflex/constants/route.py b/reflex/constants/route.py index aa301e230de..9b0455f728a 100644 --- a/reflex/constants/route.py +++ b/reflex/constants/route.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.constants.route.""" from reflex_base.constants.route import * # pragma: no cover diff --git a/reflex/constants/state.py b/reflex/constants/state.py index 3782112b6fa..9f953ccf490 100644 --- a/reflex/constants/state.py +++ b/reflex/constants/state.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.constants.state import * # pragma: no cover diff --git a/reflex/constants/utils.py b/reflex/constants/utils.py index 0c983c73dfd..dd6aaae4c32 100644 --- a/reflex/constants/utils.py +++ b/reflex/constants/utils.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.constants.utils.""" from reflex_base.constants.utils import * # pragma: no cover diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py index 6b612a0628f..6865a3cbbf2 100644 --- a/reflex/custom_components/custom_components.py +++ b/reflex/custom_components/custom_components.py @@ -618,7 +618,7 @@ def _make_pyi_files(): for top_level_dir in Path.cwd().iterdir(): if not top_level_dir.is_dir() or top_level_dir.name.startswith("."): continue - for dir, _, _ in top_level_dir.walk(): + for dir, _, _ in top_level_dir.walk(): # ty:ignore[unresolved-attribute] if "__pycache__" in dir.name: continue PyiGenerator().scan_all([dir]) diff --git a/reflex/environment.py b/reflex/environment.py index e0dbb564d1e..cf8e3bf0fde 100644 --- a/reflex/environment.py +++ b/reflex/environment.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.environment.""" from reflex_base.environment import * # pragma: no cover diff --git a/reflex/event.py b/reflex/event.py index fde5429e092..1a930f2773a 100644 --- a/reflex/event.py +++ b/reflex/event.py @@ -2,7 +2,7 @@ import sys -from reflex_base.event import * # pyright: ignore[reportWildcardImportFromLibrary] +from reflex_base.event import * from reflex_base.event import event -sys.modules[__name__] = event # pyright: ignore[reportArgumentType] +sys.modules[__name__] = event # ty:ignore[invalid-assignment] diff --git a/reflex/experimental/memo.py b/reflex/experimental/memo.py index b5a18e3f26c..8b862bff03c 100644 --- a/reflex/experimental/memo.py +++ b/reflex/experimental/memo.py @@ -7,6 +7,7 @@ from collections.abc import Callable from copy import copy from functools import cache, update_wrapper +from types import FunctionType from typing import Any, ClassVar, get_args, get_origin, get_type_hints from reflex_base import constants @@ -59,7 +60,7 @@ class MemoParam: class ExperimentalMemoDefinition: """Base metadata for an experimental memo.""" - fn: Callable[..., Any] + fn: FunctionType python_name: str params: tuple[MemoParam, ...] @@ -471,7 +472,7 @@ def _placeholder_for_param(param: MemoParam) -> Var: def _evaluate_memo_function( - fn: Callable[..., Any], + fn: FunctionType, params: tuple[MemoParam, ...], ) -> Any: """Evaluate a memo function with placeholder vars. @@ -547,7 +548,7 @@ def _lift_rest_props(component: Component) -> Component: def _analyze_params( - fn: Callable[..., Any], + fn: FunctionType, *, for_component: bool, ) -> tuple[MemoParam, ...]: @@ -565,28 +566,29 @@ def _analyze_params( """ signature = inspect.signature(fn) hints = get_type_hints(fn) + fn_name = fn.__name__ params: list[MemoParam] = [] rest_count = 0 for parameter in signature.parameters.values(): if parameter.kind is inspect.Parameter.VAR_POSITIONAL: - msg = f"`@rx._x.memo` does not support `*args` in `{fn.__name__}`." + msg = f"`@rx._x.memo` does not support `*args` in `{fn_name}`." raise TypeError(msg) if parameter.kind is inspect.Parameter.VAR_KEYWORD: - msg = f"`@rx._x.memo` does not support `**kwargs` in `{fn.__name__}`." + msg = f"`@rx._x.memo` does not support `**kwargs` in `{fn_name}`." raise TypeError(msg) if parameter.kind is inspect.Parameter.POSITIONAL_ONLY: msg = ( f"`@rx._x.memo` does not support positional-only parameters in " - f"`{fn.__name__}`." + f"`{fn_name}`." ) raise TypeError(msg) annotation = hints.get(parameter.name, parameter.annotation) if annotation is inspect.Parameter.empty: msg = ( - f"All parameters of `{fn.__name__}` must be annotated as `rx.Var[...]` " + f"All parameters of `{fn_name}` must be annotated as `rx.Var[...]` " f"or `rx.RestProp`. Missing annotation for `{parameter.name}`." ) raise TypeError(msg) @@ -598,14 +600,14 @@ def _analyze_params( if parameter.name == "children" and not is_children: msg = ( - f"`children` in `{fn.__name__}` must be annotated as " + f"`children` in `{fn_name}` must be annotated as " "`rx.Var[rx.Component]`." ) raise TypeError(msg) if not is_rest and not _is_var_annotation(annotation): msg = ( - f"All parameters of `{fn.__name__}` must be annotated as `rx.Var[...]` " + f"All parameters of `{fn_name}` must be annotated as `rx.Var[...]` " f"or `rx.RestProp`, got `{annotation}` for `{parameter.name}`." ) raise TypeError(msg) @@ -613,9 +615,7 @@ def _analyze_params( if is_rest: rest_count += 1 if rest_count > 1: - msg = ( - f"`@rx._x.memo` only supports one `rx.RestProp` in `{fn.__name__}`." - ) + msg = f"`@rx._x.memo` only supports one `rx.RestProp` in `{fn_name}`." raise TypeError(msg) js_prop_name = format.to_camel_case(parameter.name) @@ -642,7 +642,7 @@ def _analyze_params( def _create_function_definition( - fn: Callable[..., Any], + fn: FunctionType, return_annotation: Any, ) -> ExperimentalMemoFunctionDefinition: """Create a definition for a var-returning memo. @@ -686,13 +686,14 @@ def _create_function_definition( params=params, function=function, imported_var=_imported_function_var( - fn.__name__, _annotation_inner_type(return_annotation) + fn.__name__, + _annotation_inner_type(return_annotation), ), ) def _create_component_definition( - fn: Callable[..., Any], + fn: FunctionType, return_annotation: Any, ) -> ExperimentalMemoComponentDefinition: """Create a definition for a component-returning memo. @@ -1111,7 +1112,7 @@ def passthrough(children: Var[Component]) -> Component: return _create_component_wrapper(definition), definition -def memo(fn: Callable[..., Any]) -> Callable[..., Any]: +def memo(fn: FunctionType) -> Callable[..., Any]: """Create an experimental memo from a function. Args: diff --git a/reflex/istate/data.py b/reflex/istate/data.py index ee99eab4952..0fa11ef1fe4 100644 --- a/reflex/istate/data.py +++ b/reflex/istate/data.py @@ -334,7 +334,7 @@ def create( # entry still accepts it because .to()/guess_type() only call .create(...), # which has a compatible signature. _var_subclasses.append( - VarSubclassEntry(ReflexURLVar, ReflexURLCastedVar, (ReflexURL,)) # pyright: ignore[reportArgumentType] + VarSubclassEntry(ReflexURLVar, ReflexURLCastedVar, (ReflexURL,)) # ty:ignore[invalid-argument-type] ) diff --git a/reflex/istate/manager/__init__.py b/reflex/istate/manager/__init__.py index 5e3d71ee0e6..84eae3a0241 100644 --- a/reflex/istate/manager/__init__.py +++ b/reflex/istate/manager/__init__.py @@ -105,7 +105,7 @@ def _coerce_token(token: StateToken[TOKEN_TYPE] | str) -> StateToken[TOKEN_TYPE] from reflex.istate.manager.token import BaseStateToken from reflex.state import State - return BaseStateToken.from_legacy_token(token, root_state=State) # type: ignore[return-value] + return BaseStateToken.from_legacy_token(token, root_state=State) # type: ignore[return-value] # ty:ignore[invalid-return-type] return token @overload @@ -189,7 +189,7 @@ async def set_state( """ @abstractmethod - @contextlib.asynccontextmanager + @contextlib.asynccontextmanager # ty:ignore[no-matching-overload] async def modify_state( self, token: StateToken[TOKEN_TYPE] | str, @@ -204,9 +204,9 @@ async def modify_state( Yields: The state for the token. """ - yield # pyright: ignore[reportReturnType] + yield # ty:ignore[invalid-yield] - @contextlib.asynccontextmanager + @contextlib.asynccontextmanager # ty:ignore[no-matching-overload] async def modify_state_with_links( self, token: StateToken[TOKEN_TYPE] | str, diff --git a/reflex/istate/manager/disk.py b/reflex/istate/manager/disk.py index 9b75533ad93..ff8b6dc2b4e 100644 --- a/reflex/istate/manager/disk.py +++ b/reflex/istate/manager/disk.py @@ -198,7 +198,7 @@ async def get_state( if state is None: state = token.cls() self.states[token.cache_key] = state - return cast(TOKEN_TYPE, state) + return state async def set_state_for_substate( self, token: StateToken[TOKEN_TYPE], substate: TOKEN_TYPE diff --git a/reflex/istate/manager/redis.py b/reflex/istate/manager/redis.py index 3a98e16c0d4..f8d2fdf70ae 100644 --- a/reflex/istate/manager/redis.py +++ b/reflex/istate/manager/redis.py @@ -467,9 +467,9 @@ async def _try_modify_state( return # Opportunistically reuse existing lock. - async with self._get_state_cached(token) as cached_state: + async with self._get_state_cached(token) as cached_state: # ty:ignore[invalid-argument-type] if cached_state is not None: - yield cached_state + yield cached_state # ty:ignore[invalid-yield] self._notify_next_waiter(self._lock_key(token)) return @@ -547,7 +547,7 @@ async def modify_state( """ token = self._coerce_token(token) while True: - async with self._try_modify_state(token, **context) as state_instance: + async with self._try_modify_state(token, **context) as state_instance: # ty:ignore[invalid-argument-type] if state_instance is not None: yield cast(TOKEN_TYPE, state_instance) return @@ -587,7 +587,8 @@ async def _get_state_cached( raise ValueError # noqa: TRY301 except ValueError: await self.get_state( - token, for_state_instance=cached_state + token, # ty:ignore[invalid-argument-type] + for_state_instance=cached_state, ) yield cast(TOKEN_TYPE, cached_state) return @@ -816,7 +817,7 @@ async def _subscribe_lock_updates(self): lock_waiter_key_pattern: self._handle_lock_contention, } async with self.redis.pubsub() as pubsub: - await pubsub.psubscribe(**handlers) # pyright: ignore[reportArgumentType] + await pubsub.psubscribe(**handlers) self._lock_updates_subscribed.set() try: async for _ in pubsub.listen(): @@ -933,7 +934,7 @@ async def _n_lock_contenders(self, lock_key: bytes) -> int: res = self.redis.scard(lock_key + b"_waiters") if inspect.isawaitable(res): res = await res - return res + return res # ty:ignore[invalid-return-type] @contextlib.asynccontextmanager async def _request_lock_release( diff --git a/reflex/istate/proxy.py b/reflex/istate/proxy.py index ce9aa3c8618..f8f8ba5cf61 100644 --- a/reflex/istate/proxy.py +++ b/reflex/istate/proxy.py @@ -220,7 +220,7 @@ def __getattr__(self, name: str) -> Any: ) raise ImmutableStateError(msg) - value = super().__getattr__(name) # pyright: ignore[reportAttributeAccessIssue] + value = super().__getattr__(name) # ty:ignore[unresolved-attribute] if not name.startswith("_self_") and isinstance(value, MutableProxy): # ensure mutations to these containers are blocked unless proxy is _mutable return ImmutableMutableProxy( @@ -310,7 +310,7 @@ async def get_state(self, state_cls: type[T_STATE]) -> T_STATE: await self.__wrapped__.get_state(state_cls), event=self._self_event, parent_state_proxy=self, - ) # pyright: ignore [reportReturnType] + ) # ty:ignore[invalid-return-type] async def _as_state_update(self, *args, **kwargs) -> StateUpdate: """Temporarily allow mutability to access parent_state. @@ -433,14 +433,11 @@ def __new__(cls, wrapped: Any, *args, **kwargs) -> MutableProxy: wrapper_cls_name, (cls,), { - dataclasses._FIELDS: getattr( # pyright: ignore [reportAttributeAccessIssue] - wrapped_cls, - dataclasses._FIELDS, # pyright: ignore [reportAttributeAccessIssue] - ), + "__dataclass_fields__": wrapped_cls.__dataclass_fields__, }, ) cls = cls.__dataclass_proxies__[wrapper_cls_name] - return super().__new__(cls) # pyright: ignore[reportArgumentType] + return super().__new__(cls) def __init__(self, wrapped: Any, state: BaseState, field_name: str): """Create a proxy for a mutable object that tracks changes. @@ -560,7 +557,7 @@ def __getattr__(self, __name: str) -> Any: Returns: The attribute value. """ - value = super().__getattr__(__name) # pyright: ignore[reportAttributeAccessIssue] + value = super().__getattr__(__name) # ty:ignore[unresolved-attribute] if callable(value): if __name in self.__mark_dirty_attrs__: @@ -571,7 +568,7 @@ def __getattr__(self, __name: str) -> Any: # Wrap special methods that may return mutable objects tied to the state. value = wrapt.FunctionWrapper( value, - self._wrap_recursive_decorator, # pyright: ignore[reportArgumentType] + self._wrap_recursive_decorator, # ty:ignore[invalid-argument-type] ) if ( @@ -602,7 +599,7 @@ def __getitem__(self, key: Any) -> Any: Returns: The item value. """ - value = super().__getitem__(key) # pyright: ignore[reportAttributeAccessIssue] + value = super().__getitem__(key) # ty:ignore[unresolved-attribute] if isinstance(key, slice) and isinstance(value, list): return [self._wrap_recursive(item) for item in value] # Recursively wrap mutable items retrieved through this proxy. @@ -614,7 +611,7 @@ def __iter__(self) -> Any: Yields: Each item value (possibly wrapped in MutableProxy). """ - for value in super().__iter__(): # pyright: ignore[reportAttributeAccessIssue] + for value in super().__iter__(): # ty:ignore[unresolved-attribute] # Recursively wrap mutable items retrieved through this proxy. yield self._wrap_recursive(value) @@ -632,7 +629,7 @@ def __delitem__(self, key: str): Args: key: The key of the item. """ - self._mark_dirty(super().__delitem__, args=(key,)) # pyright: ignore[reportAttributeAccessIssue] + self._mark_dirty(super().__delitem__, args=(key,)) # ty:ignore[unresolved-attribute] def __setitem__(self, key: str, value: Any): """Set the item on the proxied object and mark state dirty. @@ -641,7 +638,7 @@ def __setitem__(self, key: str, value: Any): key: The key of the item. value: The value of the item. """ - self._mark_dirty(super().__setitem__, args=(key, value)) # pyright: ignore[reportAttributeAccessIssue] + self._mark_dirty(super().__setitem__, args=(key, value)) # ty:ignore[unresolved-attribute] def __setattr__(self, name: str, value: Any): """Set the attribute on the proxied object and mark state dirty. @@ -734,7 +731,7 @@ def _json_encoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any: return _orig_json_encoder_default(self, o) -json.JSONEncoder.default = _json_encoder_default_wrapper +json.JSONEncoder.default = _json_encoder_default_wrapper # ty:ignore[invalid-assignment] class ImmutableMutableProxy(MutableProxy): @@ -744,6 +741,8 @@ class ImmutableMutableProxy(MutableProxy): to modify the wrapped object when the StateProxy is immutable. """ + _self_state: StateProxy + # Ensure that recursively wrapped proxies use ImmutableMutableProxy as base. __base_proxy__ = "ImmutableMutableProxy" @@ -770,7 +769,7 @@ def _mark_dirty( Raises: ImmutableStateError: if the StateProxy is not mutable. """ - if not self._self_state._is_mutable(): # pyright: ignore[reportAttributeAccessIssue] + if not self._self_state._is_mutable(): msg = ( "Background task StateProxy is immutable outside of a context " "manager. Use `async with self` to modify state." diff --git a/reflex/istate/shared.py b/reflex/istate/shared.py index 41b1f519cd3..d3eb05a95fd 100644 --- a/reflex/istate/shared.py +++ b/reflex/istate/shared.py @@ -402,10 +402,8 @@ async def _modify_linked_states( # Go through all linked states and patch them in if they are present in the tree for linked_state_name, linked_token in self._reflex_internal_links.items(): linked_state_cls: type[SharedState] = ( - self.get_root_state().get_class_substate( # pyright: ignore[reportAssignmentType] - linked_state_name - ) - ) + self.get_root_state().get_class_substate(linked_state_name) + ) # ty:ignore[invalid-assignment] try: original_state = self._get_state_from_cache(linked_state_cls) except ValueError: diff --git a/reflex/model.py b/reflex/model.py index a57078a2fdc..648e433b112 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -51,7 +51,7 @@ def __init__(self, *args, **kwargs): _print_db_not_available(*args, **kwargs) -if find_spec("sqlalchemy"): +if TYPE_CHECKING or find_spec("sqlalchemy"): import sqlalchemy import sqlalchemy.exc import sqlalchemy.ext.asyncio @@ -257,14 +257,14 @@ def get_metadata(cls) -> sqlalchemy.MetaData: return metadata -else: +elif not TYPE_CHECKING: get_engine_args = _print_db_not_available get_engine = _print_db_not_available get_async_engine = _print_db_not_available sqla_session = _print_db_not_available - ModelRegistry = _ClassThatErrorsOnInit # pyright: ignore [reportAssignmentType] + ModelRegistry = _ClassThatErrorsOnInit -if find_spec("sqlalchemy") and find_spec("alembic"): +if TYPE_CHECKING or (find_spec("sqlalchemy") and find_spec("alembic")): import alembic.autogenerate import alembic.command import alembic.config @@ -574,7 +574,7 @@ class Model(sqlmodel.SQLModel): id: int | None = sqlmodel.Field(default=None, primary_key=True) - model_config = { # pyright: ignore [reportAssignmentType] + model_config = { "arbitrary_types_allowed": True, "use_enum_values": True, "extra": "allow", @@ -713,8 +713,8 @@ def asession(url: str | None = None) -> AsyncSession: ) return _AsyncSessionLocal[url]() -else: +elif not TYPE_CHECKING: get_db_status = _print_db_not_available session = _print_db_not_available asession = _print_db_not_available - Model = _ClassThatErrorsOnInit # pyright: ignore [reportAssignmentType] + Model = _ClassThatErrorsOnInit diff --git a/reflex/page.py b/reflex/page.py index 2e3f8fc613e..435e18513ad 100644 --- a/reflex/page.py +++ b/reflex/page.py @@ -122,4 +122,4 @@ def __new__( page_namespace = PageNamespace -sys.modules[__name__] = page_namespace # pyright: ignore[reportArgumentType] +sys.modules[__name__] = page_namespace # ty:ignore[invalid-assignment] diff --git a/reflex/plugins/_screenshot.py b/reflex/plugins/_screenshot.py index bd0bbb878bd..a73a2b2dd60 100644 --- a/reflex/plugins/_screenshot.py +++ b/reflex/plugins/_screenshot.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins._screenshot.""" from reflex_base.plugins._screenshot import * # pragma: no cover diff --git a/reflex/plugins/base.py b/reflex/plugins/base.py index c7f85b406cc..535102b293b 100644 --- a/reflex/plugins/base.py +++ b/reflex/plugins/base.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins.base.""" from reflex_base.plugins.base import * # pragma: no cover diff --git a/reflex/plugins/shared_tailwind.py b/reflex/plugins/shared_tailwind.py index ae1d730334d..16bb2425e85 100644 --- a/reflex/plugins/shared_tailwind.py +++ b/reflex/plugins/shared_tailwind.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins.shared_tailwind.""" from reflex_base.plugins.shared_tailwind import * # pragma: no cover diff --git a/reflex/plugins/sitemap.py b/reflex/plugins/sitemap.py index de79b9c18ed..02ddf01b9cb 100644 --- a/reflex/plugins/sitemap.py +++ b/reflex/plugins/sitemap.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins.sitemap.""" from reflex_base.plugins.sitemap import * # pragma: no cover diff --git a/reflex/plugins/tailwind_v3.py b/reflex/plugins/tailwind_v3.py index a5baf1b5c70..95c1f702260 100644 --- a/reflex/plugins/tailwind_v3.py +++ b/reflex/plugins/tailwind_v3.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins.tailwind_v3.""" from reflex_base.plugins.tailwind_v3 import * # pragma: no cover diff --git a/reflex/plugins/tailwind_v4.py b/reflex/plugins/tailwind_v4.py index 177e12c219f..2102166f8de 100644 --- a/reflex/plugins/tailwind_v4.py +++ b/reflex/plugins/tailwind_v4.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.plugins.tailwind_v4.""" from reflex_base.plugins.tailwind_v4 import * # pragma: no cover diff --git a/reflex/reflex.py b/reflex/reflex.py index daa63ba4187..1b37c090446 100644 --- a/reflex/reflex.py +++ b/reflex/reflex.py @@ -930,7 +930,7 @@ def _convert_reflex_loglevel_to_reflex_cli_loglevel( if find_spec("typer") and find_spec("typer.main"): - import typer # pyright: ignore[reportMissingImports] + import typer if isinstance(hosting_cli, typer.Typer): hosting_cli_command = typer.main.get_command(hosting_cli) diff --git a/reflex/state.py b/reflex/state.py index e3e959a2d44..aca5f700182 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -59,6 +59,7 @@ ComputedVar, DynamicRouteVar, EvenMoreBasicBaseState, + LiteralVar, Var, computed_var, dispatch, @@ -300,7 +301,7 @@ def _override_base_method(fn: Callable[PARAMS, RETURN]) -> Callable[PARAMS, RETU Returns: The marked function. """ - fn.__override_base_method__ = True # pyright: ignore[reportFunctionMemberAccess] + fn.__override_base_method__ = True # ty:ignore[unresolved-attribute] return fn @@ -669,7 +670,10 @@ def __init_subclass__(cls, mixin: bool = False, **kwargs): if name in cls.inherited_vars: continue if is_computed_var(value): - fget = cls._copy_fn(value.fget) + fget = value.fget + if not isinstance(fget, FunctionType): + continue + fget = cls._copy_fn(fget) newcv = value._replace(fget=fget, _var_data=VarData.from_state(cls)) # cleanup refs to mixin cls in var_data setattr(cls, name, newcv) @@ -682,6 +686,8 @@ def __init_subclass__(cls, mixin: bool = False, **kwargs): continue if parent_state is not None and parent_state.event_handlers.get(name): continue + if not isinstance(value, FunctionType): + continue value = cls._copy_fn(value) value.__qualname__ = f"{cls.__name__}.{name}" events[name] = value @@ -719,7 +725,7 @@ def _add_event_handler( setattr(cls, name, handler) @staticmethod - def _copy_fn(fn: Callable) -> Callable: + def _copy_fn(fn: FunctionType) -> FunctionType: """Copy a function. Used to copy ComputedVars and EventHandlers from mixins. Args: @@ -763,7 +769,7 @@ def _item_is_event_handler(name: str, value: Any) -> bool: ) @classmethod - def _evaluate(cls, f: Callable[[Self], Any], of_type: type | None = None) -> Var: + def _evaluate(cls, f: FunctionType, of_type: type | None = None) -> Var: """Evaluate a function to a ComputedVar. Experimental. Args: @@ -849,7 +855,7 @@ def _handle_local_def(cls): @classmethod @functools.cache - def _get_type_hints(cls) -> dict[str, Any]: + def _get_type_hints(cls) -> builtins.dict[str, Any]: """Get the type hints for this class. If the class is dynamic, evaluate the type hints with the original @@ -1294,7 +1300,7 @@ def _get_var_default(cls, name: str, annotation_value: Any) -> Any: return None @staticmethod - def _get_base_functions() -> dict[str, FunctionType]: + def _get_base_functions() -> builtins.dict[str, FunctionType]: """Get all functions of the state class excluding dunder methods. Returns: @@ -1307,7 +1313,7 @@ def _get_base_functions() -> dict[str, FunctionType]: } @classmethod - def _update_substate_inherited_vars(cls, vars_to_add: dict[str, Var]): + def _update_substate_inherited_vars(cls, vars_to_add: Mapping[str, Var]): """Update the inherited vars of substates recursively when new vars are added. Also updates the var dependency tracking dicts after adding vars. @@ -1328,7 +1334,7 @@ def _update_substate_inherited_vars(cls, vars_to_add: dict[str, Var]): cls._init_var_dependency_dicts() @classmethod - def setup_dynamic_args(cls, args: dict[str, str]): + def setup_dynamic_args(cls, args: builtins.dict[str, str]): """Set up args for easy access in renderer. Args: @@ -1439,7 +1445,7 @@ def _get_attribute(self, name: str) -> Any: else: fn = functools.partial(handler.fn, self) fn.__module__ = handler.fn.__module__ - fn.__qualname__ = handler.fn.__qualname__ + fn.__qualname__ = handler.fn.__qualname__ # ty:ignore[unresolved-attribute] return fn backend_vars = super().__getattribute__("_backend_vars") or {} @@ -1739,13 +1745,9 @@ async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE: if not isinstance(var, Var): return var - unset = object() - # Fast case: this is a literal var and the value is known. - if ( - var_value := getattr(var, "_var_value", unset) - ) is not unset and not isinstance(var_value, Var): - return var_value # pyright: ignore [reportReturnType] + if isinstance(var, LiteralVar) and not isinstance(var._var_value, Var): + return var._var_value var_data = var._get_all_var_data() if var_data is None or not var_data.state: @@ -1948,7 +1950,7 @@ def get_value(self, key: str) -> Any: def dict( self, include_computed: bool = True, initial: bool = False, **kwargs - ) -> dict[str, Any]: + ) -> builtins.dict[str, Any]: """Convert the object to a dictionary. Args: @@ -2045,7 +2047,7 @@ def __getstate__(self): state.pop(inherited_var_name, None) return state - def __setstate__(self, state: dict[str, Any]): + def __setstate__(self, state: builtins.dict[str, Any]): """Set the state from redis deserialization. This method is called by pickle to deserialize the object. @@ -2255,7 +2257,7 @@ async def _get_state_from_redis(self, state_cls: type[T_STATE]) -> T_STATE: from reflex.istate.shared import SharedStateBaseInternal shared_base = await self.get_state(SharedStateBaseInternal) - return await shared_base._resolve_linked_state(state_cls, linked_token) # type: ignore[return-value] + return await shared_base._resolve_linked_state(state_cls, linked_token) # type: ignore[return-value] # ty:ignore[invalid-return-type] return await super()._get_state_from_redis(state_cls) @event diff --git a/reflex/style.py b/reflex/style.py index 7bea29b6a8e..86dd70eb1c4 100644 --- a/reflex/style.py +++ b/reflex/style.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.style import * # pragma: no cover diff --git a/reflex/testing.py b/reflex/testing.py index 3e23afdaae8..d9ce3541de1 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -30,6 +30,7 @@ from reflex_base.config import get_config from reflex_base.environment import environment from reflex_base.registry import RegistrationContext +from reflex_base.utils.format import callable_name from reflex_base.utils.types import ASGIApp from typing_extensions import Self @@ -62,11 +63,11 @@ # The timeout (minutes) to check for the port. DEFAULT_TIMEOUT = 15 POLL_INTERVAL = 0.25 -FRONTEND_POPEN_ARGS = {} +FRONTEND_POPEN_ARGS: dict[str, Any] = {} T = TypeVar("T") TimeoutType = int | float | None if platform.system() == "Windows": - FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue] + FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # ty:ignore[unresolved-attribute] FRONTEND_POPEN_ARGS["shell"] = True else: FRONTEND_POPEN_ARGS["start_new_session"] = True @@ -119,7 +120,7 @@ class AppHarness: backend: uvicorn.Server | None = None _frontends: list[WebDriver] = dataclasses.field(default_factory=list) _registry_token: contextvars.Token[RegistrationContext] | None = None - _base_registration_context: ClassVar[RegistrationContext] | None = None + _base_registration_context: ClassVar[RegistrationContext] | None = None # ty:ignore[invalid-type-form] @classmethod def create( @@ -151,14 +152,14 @@ def create( elif isinstance(app_source, functools.partial): keywords = app_source.keywords slug_suffix = "_".join([str(v) for v in keywords.values()]) - func_name = app_source.func.__name__ + func_name = callable_name(app_source.func) app_name = f"{func_name}_{slug_suffix}" app_name = re.sub(r"[^a-zA-Z0-9_]", "_", app_name) elif isinstance(app_source, str): msg = "app_name must be provided when app_source is a string." raise ValueError(msg) else: - app_name = app_source.__name__ + app_name = callable_name(app_source) app_name = app_name.lower() while "__" in app_name: @@ -248,7 +249,7 @@ def _initialize_app(self): if self.app_source is not None: app_globals = self._get_globals_from_signature(self.app_source) if isinstance(self.app_source, functools.partial): - self.app_source = self.app_source.func + self.app_source = self.app_source.func # ty:ignore[invalid-assignment] # get the source from a function or module object source_code = "\n".join([ "\n".join([ @@ -402,12 +403,12 @@ def _wait_frontend(self): msg = "Frontend did not start" raise RuntimeError(msg) + stdout = self.frontend_process.stdout + def consume_frontend_output(): while True: try: - line = ( - self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess] - ) + line = stdout.readline() # catch I/O operation on closed file. except ValueError as e: console.error(str(e)) @@ -634,29 +635,29 @@ def frontend( want_headless = True if driver_clz is None: requested_driver = environment.APP_HARNESS_DRIVER.get() - driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable] + driver_clz = getattr(webdriver, requested_driver) if driver_options is None: - driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable] - if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable] + driver_options = getattr(webdriver, f"{requested_driver}Options")() + if driver_clz is webdriver.Chrome: if driver_options is None: from selenium.webdriver.chrome.options import Options - driver_options = Options() # pyright: ignore [reportPossiblyUnboundVariable] + driver_options = Options() driver_options.add_argument("--class=AppHarness") if want_headless: driver_options.add_argument("--headless=new") - elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable] + elif driver_clz is webdriver.Firefox: if driver_options is None: from selenium.webdriver.firefox.options import Options - driver_options = Options() # pyright: ignore [reportPossiblyUnboundVariable] + driver_options = Options() if want_headless: driver_options.add_argument("-headless") - elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable] + elif driver_clz is webdriver.Edge: if driver_options is None: from selenium.webdriver.edge.options import Options - driver_options = Options() # pyright: ignore [reportPossiblyUnboundVariable] + driver_options = Options() if want_headless: driver_options.add_argument("headless") if driver_options is None: @@ -673,7 +674,7 @@ def frontend( driver_options.set_capability(key, value) if driver_kwargs is None: driver_kwargs = {} - driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType] + driver = driver_clz(options=driver_options, **driver_kwargs) driver.get(self.frontend_url) self._frontends.append(driver) return driver diff --git a/reflex/utils/compat.py b/reflex/utils/compat.py index fa8ecc8f9a4..c58106c8654 100644 --- a/reflex/utils/compat.py +++ b/reflex/utils/compat.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.compat import * # pragma: no cover diff --git a/reflex/utils/console.py b/reflex/utils/console.py index 6c884425034..2ebeeac662b 100644 --- a/reflex/utils/console.py +++ b/reflex/utils/console.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.console import * # pragma: no cover diff --git a/reflex/utils/decorator.py b/reflex/utils/decorator.py index 6846799fcd9..2bb924b5228 100644 --- a/reflex/utils/decorator.py +++ b/reflex/utils/decorator.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.decorator import * # pragma: no cover diff --git a/reflex/utils/exceptions.py b/reflex/utils/exceptions.py index c08487e6e96..ee4c8a37ec4 100644 --- a/reflex/utils/exceptions.py +++ b/reflex/utils/exceptions.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.exceptions import * # pragma: no cover diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index 60434fc6570..96b739db446 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -242,7 +242,7 @@ def run_process_and_launch_url( } } if constants.IS_WINDOWS and backend_present: - kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue] + kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # ty:ignore[unresolved-attribute] process = processes.new_process( run_command, cwd=get_web_dir(), diff --git a/reflex/utils/format.py b/reflex/utils/format.py index 1a168466b76..8ed7a0b63be 100644 --- a/reflex/utils/format.py +++ b/reflex/utils/format.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.format import * # pragma: no cover diff --git a/reflex/utils/imports.py b/reflex/utils/imports.py index 3b93770f60e..be6a1f4e811 100644 --- a/reflex/utils/imports.py +++ b/reflex/utils/imports.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.imports import * # pragma: no cover diff --git a/reflex/utils/lazy_loader.py b/reflex/utils/lazy_loader.py index 7c1a5ca3a59..b895936b937 100644 --- a/reflex/utils/lazy_loader.py +++ b/reflex/utils/lazy_loader.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.utils.lazy_loader.""" from reflex_base.utils.lazy_loader import * # pragma: no cover diff --git a/reflex/utils/path_ops.py b/reflex/utils/path_ops.py index 6e4da438e7d..17dfa69ee4a 100644 --- a/reflex/utils/path_ops.py +++ b/reflex/utils/path_ops.py @@ -7,6 +7,7 @@ import re import shutil import stat +from collections.abc import Mapping from pathlib import Path from reflex_base.config import get_config @@ -224,7 +225,7 @@ def get_bun_path() -> Path | None: return bun_path.absolute() if bun_path else None -def update_json_file(file_path: str | Path, update_dict: dict[str, object]): +def update_json_file(file_path: str | Path, update_dict: Mapping[str, object]): """Update the contents of a json file. Args: diff --git a/reflex/utils/prerequisites.py b/reflex/utils/prerequisites.py index 29a2d75d924..3634c6cfaf8 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -328,7 +328,7 @@ def _safe_getenv(k: str, fallback: str | None = None) -> str | None: try: import nt - if not nt._supports_virtual_terminal(): # pyright: ignore[reportAttributeAccessIssue] + if not nt._supports_virtual_terminal(): return False except (ImportError, AttributeError): return False @@ -370,7 +370,7 @@ def compile_or_validate_app( try: colorize = _can_colorize() - traceback.print_exception(e, colorize=colorize) # pyright: ignore[reportCallIssue] + traceback.print_exception(e, colorize=colorize) # ty:ignore[no-matching-overload] except Exception: traceback.print_exception(e) return False diff --git a/reflex/utils/processes.py b/reflex/utils/processes.py index 71a74a01df5..be5061239dd 100644 --- a/reflex/utils/processes.py +++ b/reflex/utils/processes.py @@ -255,12 +255,12 @@ def subprocess_p_open(args: subprocess._CMD, **kwargs): fn: Callable[..., subprocess.CompletedProcess[str] | subprocess.Popen[str]] = ( subprocess.run if run else subprocess_p_open ) - return fn(non_empty_args, **kwargs) + return fn(non_empty_args, **kwargs) # ty:ignore[no-matching-overload] @contextlib.contextmanager def run_concurrently_context( - *fns: Callable[..., Any] | tuple[Callable[..., Any], ...], + *fns: Callable[..., Any] | tuple[Any, ...], ) -> Generator[list[futures.Future], None, None]: """Run functions concurrently in a thread pool. @@ -283,7 +283,7 @@ def run_concurrently_context( try: executor = futures.ThreadPoolExecutor(max_workers=len(fns)) # Submit the tasks. - tasks = [executor.submit(*fn) for fn in fns] + tasks = [executor.submit(*fn) for fn in fns] # ty:ignore[invalid-argument-type] # Yield control back to the main thread while tasks are running. yield tasks diff --git a/reflex/utils/pyi_generator.py b/reflex/utils/pyi_generator.py index 02c8dbd99cd..8e3e1a96a25 100644 --- a/reflex/utils/pyi_generator.py +++ b/reflex/utils/pyi_generator.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.pyi_generator import * # pragma: no cover diff --git a/reflex/utils/serializers.py b/reflex/utils/serializers.py index 53bdb151e7b..60d36df58c3 100644 --- a/reflex/utils/serializers.py +++ b/reflex/utils/serializers.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.serializers import * # pragma: no cover diff --git a/reflex/utils/tasks.py b/reflex/utils/tasks.py index 99dd15ee4e3..e48a2d1d36d 100644 --- a/reflex/utils/tasks.py +++ b/reflex/utils/tasks.py @@ -7,6 +7,7 @@ from typing import Any from reflex_base.utils import console +from reflex_base.utils.format import callable_name async def _run_forever( @@ -31,6 +32,7 @@ async def _run_forever( """ last_regular_loop_start = 0 exception_count = 0 + fn_name = callable_name(coro_function) while True: # Reset the exception count when the limit window has elapsed since the last non-exception loop started. @@ -47,10 +49,10 @@ async def _run_forever( exception_count += 1 if exception_count >= exception_limit: console.error( - f"{coro_function.__name__}: task exceeded exception limit {exception_limit} within {exception_limit_window}s: {e}" + f"{fn_name}: task exceeded exception limit {exception_limit} within {exception_limit_window}s: {e}" ) raise - console.error(f"{coro_function.__name__}: task error suppressed: {e}") + console.error(f"{fn_name}: task error suppressed: {e}") await asyncio.sleep(exception_delay) continue raise @@ -105,7 +107,8 @@ def ensure_task( exception_limit_window=exception_limit_window, **kwargs, ) - task_name = f"reflex_ensure_task|{type(owner).__name__}.{task_attribute}={coro_function.__name__}|{time.time()}" + fn_name = callable_name(coro_function) + task_name = f"reflex_ensure_task|{type(owner).__name__}.{task_attribute}={fn_name}|{time.time()}" if task_context is not None: # Run the task in the given context (not needed after Python 3.11+ which supports passing context to create_task directly). task = task_context.run(asyncio.create_task, rf_coro, name=task_name) diff --git a/reflex/utils/telemetry.py b/reflex/utils/telemetry.py index c2866a127c0..ca1d42e85f9 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -60,7 +60,7 @@ def _retrieve_cpu_info() -> CpuInfo | None: The CPU info. """ platform_os = platform.system() - cpuinfo = {} + cpuinfo: dict[str, Any] = {} try: if platform_os == "Windows": cmd = 'powershell -Command "Get-CimInstance Win32_Processor | Select-Object -First 1 | Select-Object AddressWidth,Manufacturer,Name | ConvertTo-Json"' diff --git a/reflex/utils/telemetry_accounting.py b/reflex/utils/telemetry_accounting.py index bda3f068b10..badaa0860ac 100644 --- a/reflex/utils/telemetry_accounting.py +++ b/reflex/utils/telemetry_accounting.py @@ -316,7 +316,7 @@ def _storage_feature_for_field(field: Field) -> FeatureName | None: """ default = field.default if isinstance(default, ClientStorageBase): - cls: type = type(default) + cls: type[ClientStorageBase] = type(default) elif isinstance(field.type_, type) and issubclass(field.type_, ClientStorageBase): cls = field.type_ else: @@ -325,6 +325,8 @@ def _storage_feature_for_field(field: Field) -> FeatureName | None: if direct is not None: return direct for ancestor in cls.__mro__: + if not issubclass(ancestor, ClientStorageBase): + continue feature = _STORAGE_FEATURE.get(ancestor) if feature is not None: return feature diff --git a/reflex/utils/types.py b/reflex/utils/types.py index e271a4755a0..0dd41e1d13c 100644 --- a/reflex/utils/types.py +++ b/reflex/utils/types.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.utils.types import * # pragma: no cover diff --git a/reflex/vars/__init__.py b/reflex/vars/__init__.py index 11d95952307..8854e8b66ad 100644 --- a/reflex/vars/__init__.py +++ b/reflex/vars/__init__.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Immutable-Based Var System.""" from reflex_base.vars import * # pragma: no cover diff --git a/reflex/vars/base.py b/reflex/vars/base.py index ebb21f5cb18..19323076605 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.base import * # pragma: no cover diff --git a/reflex/vars/color.py b/reflex/vars/color.py index 2b53da8dced..bd6da9bd19d 100644 --- a/reflex/vars/color.py +++ b/reflex/vars/color.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.color import * # pragma: no cover diff --git a/reflex/vars/datetime.py b/reflex/vars/datetime.py index 8a1beb83e60..479450b042f 100644 --- a/reflex/vars/datetime.py +++ b/reflex/vars/datetime.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.datetime import * # pragma: no cover diff --git a/reflex/vars/dep_tracking.py b/reflex/vars/dep_tracking.py index d2bdb2a3144..c4cee730dc6 100644 --- a/reflex/vars/dep_tracking.py +++ b/reflex/vars/dep_tracking.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.dep_tracking import * # pragma: no cover diff --git a/reflex/vars/function.py b/reflex/vars/function.py index 126f11e7ffc..9b7a62a3906 100644 --- a/reflex/vars/function.py +++ b/reflex/vars/function.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.function import * # pragma: no cover diff --git a/reflex/vars/number.py b/reflex/vars/number.py index b76889a407e..fabf4a62194 100644 --- a/reflex/vars/number.py +++ b/reflex/vars/number.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.number import * # pragma: no cover diff --git a/reflex/vars/object.py b/reflex/vars/object.py index 898093c6666..71fb0fc21b9 100644 --- a/reflex/vars/object.py +++ b/reflex/vars/object.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.object import * # pragma: no cover diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py index 7bfdd606ede..2afa4af0d66 100644 --- a/reflex/vars/sequence.py +++ b/reflex/vars/sequence.py @@ -1,4 +1,3 @@ -# pyright: reportWildcardImportFromLibrary=false """Re-export from reflex_base.""" from reflex_base.vars.sequence import * # pragma: no cover diff --git a/tests/benchmarks/test_event_processing.py b/tests/benchmarks/test_event_processing.py index 15acf8094d4..ce5f5a1e7e5 100644 --- a/tests/benchmarks/test_event_processing.py +++ b/tests/benchmarks/test_event_processing.py @@ -90,7 +90,7 @@ async def run_events(num_events: int, num_expected_deltas: int) -> None: async with processor as p: async for _ in asyncio.as_completed([ await p.enqueue(token, event) for _ in range(num_events) - ]): + ]): # ty:ignore[not-iterable] pass assert len(emitted_deltas) == num_expected_deltas diff --git a/tests/integration/test_background_task.py b/tests/integration/test_background_task.py index 283dbe4cd12..792e6892e46 100644 --- a/tests/integration/test_background_task.py +++ b/tests/integration/test_background_task.py @@ -334,9 +334,7 @@ def test_background_task( AppHarness.expect(lambda: counter.text == "620", timeout=40) AppHarness.expect(lambda: counter_async_cv.text == "620", timeout=40) # all tasks should have exited and cleaned up - AppHarness.expect( - lambda: not background_task.app_instance.event_processor._tasks # pyright: ignore [reportOptionalMemberAccess] - ) + AppHarness.expect(lambda: not background_task.app_instance.event_processor._tasks) # ty:ignore[unresolved-attribute] def test_nested_async_with_self( diff --git a/tests/integration/test_component_state.py b/tests/integration/test_component_state.py index b9e3a9047bc..94a122b1839 100644 --- a/tests/integration/test_component_state.py +++ b/tests/integration/test_component_state.py @@ -29,12 +29,12 @@ class MultiCounter(rx.ComponentState, Generic[E]): @rx.event def increment(self): self.count += 1 - self._be = self.count # pyright: ignore [reportAttributeAccessIssue] + self._be = self.count # ty:ignore[invalid-assignment] @rx.event def assert_be(self, value: E): assert self._backend_vars != self.backend_vars - assert self._be == int(value) # pyright: ignore [reportAttributeAccessIssue, reportArgumentType] + assert self._be == int(value) # ty:ignore[invalid-argument-type] @rx.event def assert_be_none(self): @@ -43,15 +43,15 @@ def assert_be_none(self): for name, value in self.backend_vars.items() if name not in self.inherited_backend_vars } - assert self._be is None # pyright: ignore [reportAttributeAccessIssue] + assert self._be is None @rx.event def assert_be_int(self, value: int): - assert self._be_int == value # pyright: ignore [reportAttributeAccessIssue] + assert self._be_int == value @rx.event def assert_be_str(self, value: str): - assert self._be_str == value # pyright: ignore [reportAttributeAccessIssue] + assert self._be_str == value @classmethod def get_component(cls, *children, **props): @@ -70,7 +70,7 @@ def get_component(cls, *children, **props): "Assert _be", id=f"{eid}-assert-be", ), - on_submit=lambda fd: cls.assert_be(fd.to(dict)["be_value"]), # pyright: ignore [reportAttributeAccessIssue] + on_submit=lambda fd: cls.assert_be(fd.to(dict)["be_value"]), reset_on_submit=True, ), rx.button( @@ -135,7 +135,7 @@ def index(): mc_d, rx.button( "Inc A", - on_click=mc_a.State.increment, # pyright: ignore [reportAttributeAccessIssue, reportOptionalMemberAccess] + on_click=mc_a.State.increment, # ty:ignore[unresolved-attribute] id="inc-a", ), rx.text( diff --git a/tests/integration/test_dynamic_components.py b/tests/integration/test_dynamic_components.py index 3de8eef034f..5c52e0ca982 100644 --- a/tests/integration/test_dynamic_components.py +++ b/tests/integration/test_dynamic_components.py @@ -8,8 +8,6 @@ from reflex.testing import AppHarness -# pyright: reportOptionalMemberAccess=false, reportGeneralTypeIssues=false, reportUnknownMemberType=false - def DynamicComponents(): """App with var operations.""" diff --git a/tests/integration/test_dynamic_routes.py b/tests/integration/test_dynamic_routes.py index 7c3e7641f86..2047e670909 100644 --- a/tests/integration/test_dynamic_routes.py +++ b/tests/integration/test_dynamic_routes.py @@ -24,7 +24,7 @@ class DynamicState(rx.State): @rx.event def on_load(self): - page_data = f"{self.router.page.path}-{self.page_id or 'no page id'}" # pyright: ignore[reportAttributeAccessIssue] + page_data = f"{self.router.page.path}-{self.page_id or 'no page id'}" # ty:ignore[unresolved-attribute] print(f"on_load: {page_data}") self.order.append(page_data) @@ -44,7 +44,7 @@ def on_load_static(self): @rx.var def next_page(self) -> str: try: - return str(int(self.page_id) + 1) # pyright: ignore[reportAttributeAccessIssue] + return str(int(self.page_id) + 1) # ty:ignore[unresolved-attribute] except ValueError: return "0" @@ -59,7 +59,7 @@ def index(): read_only=True, id="token", ), - rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # pyright: ignore [reportAttributeAccessIssue] + rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # ty:ignore[unresolved-attribute] rx.input( value=DynamicState.router.page.raw_path, read_only=True, @@ -75,7 +75,7 @@ def index(): rx.link("missing", href="/missing", id="link_missing"), rx.vstack( rx.foreach( - DynamicState.order, # pyright: ignore [reportAttributeAccessIssue] + DynamicState.order, rx.text, ), id="event_order", @@ -88,7 +88,7 @@ class ArgState(rx.State): @rx.var(cache=False) def arg(self) -> int: - return int(self.arg_str or 0) # pyright: ignore[reportAttributeAccessIssue] + return int(self.arg_str or 0) # ty:ignore[unresolved-attribute] class ArgSubState(ArgState): @rx.var @@ -97,7 +97,7 @@ def cached_arg(self) -> int: @rx.var def cached_arg_str(self) -> str: - return self.arg_str # pyright: ignore[reportAttributeAccessIssue] + return self.arg_str # ty:ignore[unresolved-attribute] @rx.page(route="/arg/[arg_str]") def arg() -> rx.Component: @@ -110,11 +110,11 @@ def arg() -> rx.Component: rx.data_list.root( rx.data_list.item( rx.data_list.label("rx.State.arg_str (dynamic)"), - rx.data_list.value(rx.State.arg_str, id="state-arg_str"), # pyright: ignore [reportAttributeAccessIssue] + rx.data_list.value(rx.State.arg_str, id="state-arg_str"), # ty:ignore[unresolved-attribute] ), rx.data_list.item( rx.data_list.label("ArgState.arg_str (dynamic) (inherited)"), - rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # pyright: ignore [reportAttributeAccessIssue] + rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # ty:ignore[unresolved-attribute] ), rx.data_list.item( rx.data_list.label("ArgState.arg"), @@ -122,7 +122,7 @@ def arg() -> rx.Component: ), rx.data_list.item( rx.data_list.label("ArgSubState.arg_str (dynamic) (inherited)"), - rx.data_list.value(ArgSubState.arg_str, id="argsubstate-arg_str"), # pyright: ignore [reportAttributeAccessIssue] + rx.data_list.value(ArgSubState.arg_str, id="argsubstate-arg_str"), # ty:ignore[unresolved-attribute] ), rx.data_list.item( rx.data_list.label("ArgSubState.arg (inherited)"), diff --git a/tests/integration/test_event_actions.py b/tests/integration/test_event_actions.py index f253c306fd1..cc72793801c 100644 --- a/tests/integration/test_event_actions.py +++ b/tests/integration/test_event_actions.py @@ -25,16 +25,19 @@ def TestEventAction(): class EventActionState(rx.State): order: list[str] - def on_click(self, ev): + @rx.event + def on_click(self, ev: str): self.order.append(f"on_click:{ev}") @rx.event def on_click2(self): self.order.append("on_click2") + @rx.event def on_click_throttle(self): self.order.append("on_click_throttle") + @rx.event def on_click_debounce(self): self.order.append("on_click_debounce") @@ -76,12 +79,12 @@ def index(): ), rx.button( "Click event", - on_click=EventActionState.on_click("no_event_actions"), # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click("no_event_actions"), id="btn-click-event", ), rx.button( "Click stop propagation", - on_click=EventActionState.on_click("stop_propagation").stop_propagation, # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click("stop_propagation").stop_propagation, id="btn-click-stop-propagation", ), rx.button( @@ -97,13 +100,13 @@ def index(): rx.link( "Link", href="?link", - on_click=EventActionState.on_click("link_no_event_actions"), # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click("link_no_event_actions"), id="link", ), rx.link( "Link Stop Propagation", href="?link-stop-propagation", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click( "link_stop_propagation" ).stop_propagation, id="link-stop-propagation", @@ -117,7 +120,7 @@ def index(): rx.link( "Link Prevent Default", href="/invalid", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click( "link_prevent_default" ).prevent_default, id="link-prevent-default", @@ -125,20 +128,20 @@ def index(): rx.link( "Link Both", href="/invalid", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click( "link_both" ).stop_propagation.prevent_default, id="link-stop-propagation-prevent-default", ), EventFiringComponent.create( id="custom-stop-propagation", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click( "custom-stop-propagation" ).stop_propagation, ), EventFiringComponent.create( id="custom-prevent-default", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click( "custom-prevent-default" ).prevent_default, ), @@ -146,15 +149,13 @@ def index(): "Throttle", id="btn-throttle", on_click=lambda: ( - EventActionState.on_click_throttle.throttle( # pyright: ignore [reportFunctionMemberAccess] - 200 - ).stop_propagation + EventActionState.on_click_throttle.throttle(200).stop_propagation ), ), rx.button( "Debounce", id="btn-debounce", - on_click=EventActionState.on_click_debounce.debounce( # pyright: ignore [reportFunctionMemberAccess] + on_click=EventActionState.on_click_debounce.debounce( 200 ).stop_propagation, ), @@ -165,7 +166,7 @@ def index(): ), id="event_order", ), - on_click=EventActionState.on_click("outer"), # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click("outer"), ), rx.form( rx.dialog.root( rx.dialog.trigger( @@ -176,12 +177,12 @@ def index(): rx.dialog.close( rx.form( rx.button("Submit", id="btn-submit"), - on_submit=EventActionState.on_submit.stop_propagation, # pyright: ignore [reportCallIssue] + on_submit=EventActionState.on_submit.stop_propagation, ), ), ), ), - on_submit=EventActionState.on_submit, # pyright: ignore [reportCallIssue] + on_submit=EventActionState.on_submit, ) app = rx.App() @@ -361,8 +362,8 @@ def test_event_actions_dialog_form_in_form( driver.find_element(By.ID, open_dialog_id).click() el = wait.until(EC.element_to_be_clickable((By.ID, submit_button_id))) - el.click() # pyright: ignore[reportAttributeAccessIssue] - el.send_keys(Keys.ESCAPE) # pyright: ignore[reportAttributeAccessIssue] + el.click() + el.send_keys(Keys.ESCAPE) btn_no_events = wait.until(EC.element_to_be_clickable((By.ID, "btn-no-events"))) btn_no_events.location_once_scrolled_into_view diff --git a/tests/integration/test_exception_handlers.py b/tests/integration/test_exception_handlers.py index 8c24cfaa45e..ce93196b1f4 100644 --- a/tests/integration/test_exception_handlers.py +++ b/tests/integration/test_exception_handlers.py @@ -32,6 +32,7 @@ class TestAppState(rx.State): def set_react_error(self, value: bool): self.react_error = value + @rx.event def divide_by_number(self, number: int): """Divide by number and print the result. @@ -53,7 +54,7 @@ def index(): ), rx.button( "induce_backend_error", - on_click=lambda: TestAppState.divide_by_number(0), # pyright: ignore [reportCallIssue] + on_click=lambda: TestAppState.divide_by_number(0), id="induce-backend-error-btn", ), rx.button( diff --git a/tests/integration/test_lifespan.py b/tests/integration/test_lifespan.py index 1f3185db86c..9938eda856e 100644 --- a/tests/integration/test_lifespan.py +++ b/tests/integration/test_lifespan.py @@ -35,9 +35,9 @@ def LifespanApp( @asynccontextmanager async def lifespan_context(app, inc: int = 1): - global lifespan_context_global + global lifespan_context_global # ty:ignore[unresolved-global] print(f"Lifespan context entered: {app}.") - lifespan_context_global += inc # pyright: ignore[reportUnboundVariable] + lifespan_context_global += inc # ty:ignore[unresolved-reference] try: yield finally: @@ -45,22 +45,22 @@ async def lifespan_context(app, inc: int = 1): lifespan_context_global += inc async def lifespan_task(inc: int = 1): - global lifespan_task_global + global lifespan_task_global # ty:ignore[unresolved-global] print("Lifespan global started.") try: while True: - lifespan_task_global += inc # pyright: ignore[reportUnboundVariable, reportPossiblyUnboundVariable] + lifespan_task_global += inc await asyncio.sleep(0.1) except asyncio.CancelledError as ce: print(f"Lifespan global cancelled: {ce}.") lifespan_task_global = 0 async def raw_asyncio_task_coro(): - global raw_asyncio_task_global + global raw_asyncio_task_global # ty:ignore[unresolved-global] print("Raw asyncio task started.") try: while True: - raw_asyncio_task_global += 1 # pyright: ignore[reportUnboundVariable, reportPossiblyUnboundVariable] + raw_asyncio_task_global += 1 await asyncio.sleep(0.1) except asyncio.CancelledError as ce: print(f"Raw asyncio task cancelled: {ce}.") diff --git a/tests/integration/test_linked_state.py b/tests/integration/test_linked_state.py index 6670b18df16..0520cab5db0 100644 --- a/tests/integration/test_linked_state.py +++ b/tests/integration/test_linked_state.py @@ -62,9 +62,9 @@ def clear_event_link_status(self): @rx.event async def on_load_link_default(self): - linked_state = await self._link_to(self.room or "default") # pyright: ignore[reportAttributeAccessIssue] - if self.room: # pyright: ignore[reportAttributeAccessIssue] - assert linked_state._linked_to == self.room # pyright: ignore[reportAttributeAccessIssue] + linked_state = await self._link_to(self.room or "default") # ty:ignore[unresolved-attribute] + if self.room: # ty:ignore[unresolved-attribute] + assert linked_state._linked_to == self.room # ty:ignore[unresolved-attribute] else: assert linked_state._linked_to == "default" @@ -82,7 +82,7 @@ class SharedNotes(rx.SharedState): @rx.event async def on_load_link_default(self): - linked_state = await self._link_to(self.room or "default") # pyright: ignore[reportAttributeAccessIssue] + linked_state = await self._link_to(self.room or "default") # ty:ignore[unresolved-attribute] initial_note = self.router.page.params.get("initial_note", "") if initial_note: linked_state.note = initial_note diff --git a/tests/integration/test_login_flow.py b/tests/integration/test_login_flow.py index 17681370d62..f6abb2ea6e2 100644 --- a/tests/integration/test_login_flow.py +++ b/tests/integration/test_login_flow.py @@ -36,8 +36,8 @@ def login(self): yield rx.redirect("/") def index(): - return rx.cond( # pyright: ignore [reportCallIssue] - State.is_hydrated & State.auth_token, # pyright: ignore [reportOperatorIssue] + return rx.cond( + State.is_hydrated & State.auth_token, # ty:ignore[unsupported-operator] rx.vstack( rx.heading(State.auth_token, id="auth-token"), rx.button("Logout", on_click=State.logout, id="logout"), diff --git a/tests/integration/test_telemetry_compile.py b/tests/integration/test_telemetry_compile.py index fd4069f9572..a669eb304aa 100644 --- a/tests/integration/test_telemetry_compile.py +++ b/tests/integration/test_telemetry_compile.py @@ -35,6 +35,7 @@ def TelemetryCompileApp(events_log_path: str = ""): import json import os from pathlib import Path + from typing import Any import reflex as rx from reflex.istate.storage import Cookie, LocalStorage, SessionStorage @@ -49,14 +50,20 @@ def TelemetryCompileApp(events_log_path: str = ""): sink = Path(events_log_path) sink.parent.mkdir(parents=True, exist_ok=True) - def _capture(event, properties=None, **_kwargs): + def _capture( + event: str, + telemetry_enabled: bool | None = None, + *, + properties: dict[str, Any] | None = None, + **_kwargs: Any, + ) -> bool: with sink.open("a") as fh: fh.write( json.dumps({"event": event, "properties": properties or {}}) + "\n" ) return True - telemetry.send = _capture + telemetry.send = _capture # ty:ignore[invalid-assignment] class StorageRoot(rx.State): token: str = Cookie() diff --git a/tests/integration/test_upload.py b/tests/integration/test_upload.py index 11e34609302..05d7913a4ee 100644 --- a/tests/integration/test_upload.py +++ b/tests/integration/test_upload.py @@ -167,7 +167,7 @@ def index(): ), rx.button( "Upload", - on_click=lambda: UploadState.handle_upload(rx.upload_files()), # pyright: ignore [reportArgumentType] + on_click=lambda: UploadState.handle_upload(rx.upload_files()), id="upload_button", ), rx.box( @@ -193,7 +193,7 @@ def index(): rx.button( "Upload", on_click=UploadState.handle_upload_secondary( - rx.upload_files( # pyright: ignore [reportArgumentType] + rx.upload_files( upload_id="secondary", on_upload_progress=UploadState.upload_progress, ), @@ -235,7 +235,7 @@ def index(): rx.button( "Upload", on_click=UploadState.handle_upload_tertiary( - rx.upload_files( # pyright: ignore [reportArgumentType] + rx.upload_files( upload_id="tertiary", ), ), @@ -257,7 +257,7 @@ def index(): rx.text("Drag and drop files here or click to select files"), ), on_drop=UploadState.handle_upload_quaternary( - rx.upload_files( # pyright: ignore [reportArgumentType] + rx.upload_files( upload_id="quaternary", ), ), @@ -278,7 +278,7 @@ def index(): rx.button( "Upload", on_click=UploadState.handle_upload_stream( - rx.upload_files_chunk( # pyright: ignore [reportArgumentType] + rx.upload_files_chunk( upload_id="streaming", on_upload_progress=UploadState.stream_upload_progress, ) diff --git a/tests/integration/test_var_operations.py b/tests/integration/test_var_operations.py index 409a0838b2e..8c7b23f5018 100644 --- a/tests/integration/test_var_operations.py +++ b/tests/integration/test_var_operations.py @@ -713,7 +713,7 @@ def index(): id="optional_list", ), rx.box( - rx.foreach(VarOperationState.optional_dict, rx.text.span), + rx.foreach(VarOperationState.optional_dict, rx.text.span), # ty:ignore[invalid-argument-type] id="optional_dict", ), rx.box( @@ -721,7 +721,7 @@ def index(): id="optional_list_value", ), rx.box( - rx.foreach(VarOperationState.optional_dict_value, rx.text.span), + rx.foreach(VarOperationState.optional_dict_value, rx.text.span), # ty:ignore[invalid-argument-type] id="optional_dict_value", ), rx.box( diff --git a/tests/integration/tests_playwright/test_appearance.py b/tests/integration/tests_playwright/test_appearance.py index a0252d6da46..45138c91f69 100644 --- a/tests/integration/tests_playwright/test_appearance.py +++ b/tests/integration/tests_playwright/test_appearance.py @@ -65,7 +65,7 @@ def index(): rx.icon(tag="moon", size=20), value="dark", ), - on_change=set_color_mode, # pyright: ignore[reportArgumentType] + on_change=set_color_mode, variant="classic", radius="large", value=color_mode, diff --git a/tests/integration/tests_playwright/test_frontend_path.py b/tests/integration/tests_playwright/test_frontend_path.py index d9709d84653..2b477361125 100644 --- a/tests/integration/tests_playwright/test_frontend_path.py +++ b/tests/integration/tests_playwright/test_frontend_path.py @@ -42,7 +42,7 @@ def on_load_static(self): @rx.event def on_load_dynamic(self): - page_id = self.page_id # pyright: ignore[reportAttributeAccessIssue] + page_id = self.page_id # ty:ignore[unresolved-attribute] self.on_load_events.append(f"dynamic-{page_id}") @rx.event @@ -121,7 +121,7 @@ def _router_info(): id="router-url-path", ), rx.input( - value=FPState.router.page.raw_path, # pyright: ignore[reportDeprecated] + value=FPState.router.page.raw_path, read_only=True, id="router-page-raw-path", ), @@ -202,7 +202,7 @@ def static_page(): @rx.page("/dynamic/[page_id]", on_load=FPState.on_load_dynamic) def dynamic_page(): return rx.box( - rx.text(f"dynamic page {rx.State.page_id}", id="page-id"), # pyright: ignore[reportAttributeAccessIssue] + rx.text(f"dynamic page {rx.State.page_id}", id="page-id"), # ty:ignore[unresolved-attribute] rx.input( value=FPState.router.session.client_token, read_only=True, diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index e2f1b769668..d6cc26a1e34 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -433,17 +433,17 @@ def test_create_document_root(): assert isinstance(root, Html) assert isinstance(root.children[0], Head) # Default language. - lang = root.lang # pyright: ignore [reportAttributeAccessIssue] + lang = root.lang # ty:ignore[unresolved-attribute] assert isinstance(lang, LiteralStringVar) assert lang.equals(Var.create("en")) # No children in head. assert len(root.children[0].children) == 6 assert isinstance(root.children[0].children[1], Meta) - char_set = root.children[0].children[1].char_set # pyright: ignore [reportAttributeAccessIssue] + char_set = root.children[0].children[1].char_set # ty:ignore[unresolved-attribute] assert isinstance(char_set, LiteralStringVar) assert char_set.equals(Var.create("utf-8")) assert isinstance(root.children[0].children[2], Meta) - name = root.children[0].children[2].name # pyright: ignore [reportAttributeAccessIssue] + name = root.children[0].children[2].name # ty:ignore[unresolved-attribute] assert isinstance(name, LiteralStringVar) assert name.equals(Var.create("viewport")) assert isinstance(root.children[0].children[3], document.Meta) @@ -475,7 +475,7 @@ def test_create_document_root_with_scripts(): "link", "Links", ] - lang = root.lang # pyright: ignore [reportAttributeAccessIssue] + lang = root.lang # ty:ignore[unresolved-attribute] assert isinstance(lang, LiteralStringVar) assert lang.equals(Var.create("rx")) assert isinstance(root.custom_attrs, dict) @@ -494,7 +494,7 @@ def test_create_document_root_with_meta_char_set(): assert len(root.children[0].children) == 6 names = [c.tag for c in root.children[0].children] assert names == ["script", "meta", "meta", "Meta", "link", "Links"] - assert str(root.children[0].children[1].char_set) == '"cp1252"' # pyright: ignore [reportAttributeAccessIssue] + assert str(root.children[0].children[1].char_set) == '"cp1252"' # ty:ignore[unresolved-attribute] def test_create_document_root_with_meta_viewport(): @@ -510,7 +510,7 @@ def test_create_document_root_with_meta_viewport(): assert len(root.children[0].children) == 7 names = [c.tag for c in root.children[0].children] assert names == ["script", "meta", "meta", "meta", "Meta", "link", "Links"] - assert str(root.children[0].children[1].http_equiv) == '"refresh"' # pyright: ignore [reportAttributeAccessIssue] - assert str(root.children[0].children[2].name) == '"viewport"' # pyright: ignore [reportAttributeAccessIssue] - assert str(root.children[0].children[2].content) == '"foo"' # pyright: ignore [reportAttributeAccessIssue] - assert str(root.children[0].children[3].char_set) == '"utf-8"' # pyright: ignore [reportAttributeAccessIssue] + assert str(root.children[0].children[1].http_equiv) == '"refresh"' # ty:ignore[unresolved-attribute] + assert str(root.children[0].children[2].name) == '"viewport"' # ty:ignore[unresolved-attribute] + assert str(root.children[0].children[2].content) == '"foo"' # ty:ignore[unresolved-attribute] + assert str(root.children[0].children[3].char_set) == '"utf-8"' # ty:ignore[unresolved-attribute] diff --git a/tests/units/compiler/test_dynamic_components_codegen.py b/tests/units/compiler/test_dynamic_components_codegen.py index 14eafa4de90..010972ebd41 100644 --- a/tests/units/compiler/test_dynamic_components_codegen.py +++ b/tests/units/compiler/test_dynamic_components_codegen.py @@ -15,7 +15,7 @@ def test_dynamic_component_codegen_wires_event_handlers() -> None: """Dynamic component codegen should preserve backend event handlers.""" - state = State(_reflex_internal_init=True) # pyright: ignore[reportCallIssue] + state = State(_reflex_internal_init=True) # ty:ignore[unknown-argument] component = rx.el.div( rx.el.button("hydrate", on_click=State.set_is_hydrated(True)), rx.el.span(state.is_hydrated), @@ -81,7 +81,7 @@ def counter_ui(self) -> rx.Component: justify="center", ) - state = DynamicCounterCodegenState(_reflex_internal_init=True) # pyright: ignore[reportCallIssue] + state = DynamicCounterCodegenState(_reflex_internal_init=True) # ty:ignore[unknown-argument] code = serializers.serialize(state.counter_ui) assert isinstance(code, str) diff --git a/tests/units/compiler/test_memoize_plugin.py b/tests/units/compiler/test_memoize_plugin.py index 755ef8914e7..96c6db42e63 100644 --- a/tests/units/compiler/test_memoize_plugin.py +++ b/tests/units/compiler/test_memoize_plugin.py @@ -307,13 +307,10 @@ def special_child() -> Component: lambda item: rx.text(item), ) if special_form == "cond": - return cast( - Component, - rx.cond( - SpecialFormMemoState.flag, - rx.text("yes"), - rx.text("no"), - ), + return rx.cond( + SpecialFormMemoState.flag, + rx.text("yes"), + rx.text("no"), ) return cast( Component, @@ -445,13 +442,10 @@ def test_common_memoization_snapshot_helper_classifies_snapshot_cases() -> None: lambda item: rx.text(item), ) ) - cond_fragment = cast( - Component, - rx.cond( - SpecialFormMemoState.flag, - rx.text("yes"), - rx.text("no"), - ), + cond_fragment = rx.cond( + SpecialFormMemoState.flag, + rx.text("yes"), + rx.text("no"), ) match_fragment = cast( Component, diff --git a/tests/units/components/core/test_colors.py b/tests/units/components/core/test_colors.py index 48b074b3103..12eac2d8f11 100644 --- a/tests/units/components/core/test_colors.py +++ b/tests/units/components/core/test_colors.py @@ -24,7 +24,7 @@ def create_color_var(color): color_with_fstring = rx.color( - f"{ColorState.color}", # pyright: ignore [reportArgumentType] + f"{ColorState.color}", # ty:ignore[invalid-argument-type] ColorState.shade, ) @@ -55,7 +55,7 @@ def create_color_var(color): ( create_color_var( rx.color( - f"{ColorState.color_part}ato", # pyright: ignore [reportArgumentType] + f"{ColorState.color_part}ato", # ty:ignore[invalid-argument-type] ColorState.shade, ) ), @@ -143,4 +143,4 @@ def test_radix_color(color, expected): expected (str): The expected custom_style string, radix or literal """ code_block = CodeBlock.create("Hello World", background_color=color) - assert str(code_block.custom_style["backgroundColor"]) == expected # pyright: ignore [reportAttributeAccessIssue] + assert str(code_block.custom_style["backgroundColor"]) == expected # ty:ignore[unresolved-attribute] diff --git a/tests/units/components/core/test_cond.py b/tests/units/components/core/test_cond.py index a3c45875417..9bea1b453da 100644 --- a/tests/units/components/core/test_cond.py +++ b/tests/units/components/core/test_cond.py @@ -17,7 +17,7 @@ @pytest.fixture def cond_state(request): class CondState(BaseState): - value: request.param["value_type"] = request.param["value"] # pyright: ignore [reportInvalidTypeForm, reportUndefinedVariable] # noqa: F821 + value: request.param["value_type"] = request.param["value"] # noqa: F821 return CondState @@ -44,7 +44,7 @@ def test_validate_cond(cond_state: BaseState): cond_state: A fixture. """ cond_component = cond( - cond_state.value, # pyright: ignore[reportAttributeAccessIssue] + cond_state.value, # ty:ignore[unresolved-attribute] Text.create("cond is True"), Text.create("cond is False"), ) @@ -52,7 +52,7 @@ def test_validate_cond(cond_state: BaseState): assert cond_dict["name"] == "Fragment" [condition] = cond_dict["children"] - assert condition["cond_state"] == str(cond_state.value.bool()) # pyright: ignore[reportAttributeAccessIssue] + assert condition["cond_state"] == str(cond_state.value.bool()) # ty:ignore[unresolved-attribute] # true value true_value = condition["true_value"] @@ -115,12 +115,12 @@ def test_cond_no_else(): comp = comp.children[0] assert isinstance(comp, Cond) assert comp.cond._decode() is True - assert comp.children[0].render() == Fragment.create(Text.create("hello")).render() # pyright: ignore [reportOptionalMemberAccess] + assert comp.children[0].render() == Fragment.create(Text.create("hello")).render() assert comp.children[1] == Fragment.create() # Props do not support the use of cond without else with pytest.raises(ValueError): - cond(True, "hello") # pyright: ignore [reportArgumentType] + cond(True, "hello") # ty:ignore[invalid-argument-type] def test_cond_render_missing_false_child_defaults_to_fragment() -> None: @@ -163,7 +163,7 @@ def computed_str(self) -> str: def test_cond_assert_types() -> None: - """Test that pyright infers the correct return types for cond overloads.""" + """Test that the type checker infers the correct return types for cond overloads.""" text_comp = Text.create("hello") text_comp2 = Text.create("world") var_int: Var[int] = LiteralVar.create(1) @@ -182,22 +182,22 @@ def test_cond_assert_types() -> None: _ = assert_type(cond(True, "hello", text_comp), Component) # T, T -> Var[T] - _ = assert_type(cond(True, "hello", "world"), Var[str]) + _ = assert_type(cond(True, "hello", "world"), Var[str]) # ty:ignore[type-assertion-failure] # T, U -> Var[T | U] - _ = assert_type(cond(True, "hello", 3), Var[str | int]) + _ = assert_type(cond(True, "hello", 3), Var[str | int]) # ty:ignore[type-assertion-failure] # T, Var[T] -> Var[T] - _ = assert_type(cond(True, "hello", var_str), Var[str]) + _ = assert_type(cond(True, "hello", var_str), Var[str]) # ty:ignore[type-assertion-failure] # Var[T], T -> Var[T] - _ = assert_type(cond(True, var_str, "world"), Var[str]) + _ = assert_type(cond(True, var_str, "world"), Var[str]) # ty:ignore[type-assertion-failure] # T, Var[U] -> Var[T | U] - _ = assert_type(cond(True, "hello", var_int), Var[str | int]) + _ = assert_type(cond(True, "hello", var_int), Var[str | int]) # ty:ignore[type-assertion-failure] # Var[T], U -> Var[T | U] - _ = assert_type(cond(True, var_str, 3), Var[int | Literal["a"]]) + _ = assert_type(cond(True, var_str, 3), Var[int | Literal["a"]]) # ty:ignore[type-assertion-failure] # Var[T], Var[U] -> Var[T | U] _ = assert_type(cond(True, var_int, var_str), Var[int | Literal["a"]]) diff --git a/tests/units/components/core/test_foreach.py b/tests/units/components/core/test_foreach.py index cec2db1c95a..57c5a4ce077 100644 --- a/tests/units/components/core/test_foreach.py +++ b/tests/units/components/core/test_foreach.py @@ -317,11 +317,11 @@ def test_optional_list(): ) Foreach.create( - ForEachState.optional_dict, + ForEachState.optional_dict, # ty:ignore[invalid-argument-type] lambda color: text(color[0], color[1]), ) Foreach.create( - ForEachState.optional_dict_value, + ForEachState.optional_dict_value, # ty:ignore[invalid-argument-type] lambda color: text(color[0], color[1]), ) diff --git a/tests/units/components/core/test_html.py b/tests/units/components/core/test_html.py index 4241c9344ab..fd53a50485c 100644 --- a/tests/units/components/core/test_html.py +++ b/tests/units/components/core/test_html.py @@ -16,7 +16,7 @@ def test_html_many_children(): def test_html_create(): html = Html.create("

Hello !

") - assert str(html.dangerouslySetInnerHTML) == '({ ["__html"] : "

Hello !

" })' # pyright: ignore [reportAttributeAccessIssue] + assert str(html.dangerouslySetInnerHTML) == '({ ["__html"] : "

Hello !

" })' # ty:ignore[unresolved-attribute] assert ( str(html) == 'jsx("div",{className:"rx-Html",dangerouslySetInnerHTML:({ ["__html"] : "

Hello !

" })},)' @@ -31,7 +31,7 @@ class TestState(State): html = Html.create(f"

Hello {TestState.myvar}!

") - html_dangerouslySetInnerHTML = html.dangerouslySetInnerHTML # pyright: ignore [reportAttributeAccessIssue] + html_dangerouslySetInnerHTML = html.dangerouslySetInnerHTML # ty:ignore[unresolved-attribute] assert ( str(html_dangerouslySetInnerHTML) diff --git a/tests/units/components/core/test_upload.py b/tests/units/components/core/test_upload.py index d3a1e4c19aa..4c6e89823a8 100644 --- a/tests/units/components/core/test_upload.py +++ b/tests/units/components/core/test_upload.py @@ -8,7 +8,7 @@ StyledUpload, Upload, UploadNamespace, - _on_drop_spec, # pyright: ignore [reportAttributeAccessIssue] + _on_drop_spec, cancel_upload, get_upload_url, ) @@ -157,7 +157,7 @@ def test_upload_create(): up_comp_5 = Upload.create( id="foo_id", on_drop=StreamingUploadStateTest.chunk_drop_handler( - rx.upload_files_chunk(upload_id="foo_id") # pyright: ignore[reportArgumentType] + rx.upload_files_chunk(upload_id="foo_id") ), ) assert isinstance(up_comp_5, Upload) @@ -166,7 +166,7 @@ def test_upload_create(): up_comp_6 = Upload.create( id="foo_id", on_drop=StreamingUploadStateTest.chunk_upload_alias_handler( - rx.upload_files_chunk(upload_id="foo_id") # pyright: ignore[reportArgumentType] + rx.upload_files_chunk(upload_id="foo_id") ), ) assert isinstance(up_comp_6, Upload) @@ -189,7 +189,7 @@ def test_upload_button_handlers_allow_custom_param_names(): chunk_button = rx.button( "Upload", on_click=StreamingUploadStateTest.chunk_upload_alias_handler( - rx.upload_files_chunk(upload_id="foo_id") # pyright: ignore[reportArgumentType] + rx.upload_files_chunk(upload_id="foo_id") ), ) chunk_chain = cast(EventChain, chunk_button.event_triggers["on_click"]) diff --git a/tests/units/components/datadisplay/test_code.py b/tests/units/components/datadisplay/test_code.py index 42b51b773e5..192c552b770 100644 --- a/tests/units/components/datadisplay/test_code.py +++ b/tests/units/components/datadisplay/test_code.py @@ -11,12 +11,12 @@ def test_code_light_dark_theme(theme, expected): code_block = CodeBlock.create(theme=theme) - assert code_block.theme._js_expr == expected # pyright: ignore [reportAttributeAccessIssue] + assert code_block.theme._js_expr == expected # ty:ignore[unresolved-attribute] def test_code_block_rejects_string_theme(): with pytest.raises(TypeError, match=r"CodeBlock\.theme"): - CodeBlock.create("print('Hello')", theme="one_dark") # pyright: ignore[reportArgumentType] + CodeBlock.create("print('Hello')", theme="one_dark") # ty:ignore[invalid-argument-type] def test_code_block_accepts_color_mode_cond_theme(): diff --git a/tests/units/components/datadisplay/test_datatable.py b/tests/units/components/datadisplay/test_datatable.py index 684248e875c..54d3ece0672 100644 --- a/tests/units/components/datadisplay/test_datatable.py +++ b/tests/units/components/datadisplay/test_datatable.py @@ -16,7 +16,7 @@ { "data": pd.DataFrame( [["foo", "bar"], ["foo1", "bar1"]], - columns=["column1", "column2"], # pyright: ignore [reportArgumentType] + columns=["column1", "column2"], ) }, "data", @@ -34,13 +34,13 @@ def test_validate_data_table(data_table_state: rx.State, expected): expected: expected var name. """ - if not types.is_dataframe(data_table_state.data._var_type): # pyright: ignore[reportAttributeAccessIssue] + if not types.is_dataframe(data_table_state.data._var_type): # ty:ignore[unresolved-attribute] data_table_component = DataTable.create( - data=data_table_state.data, # pyright: ignore[reportAttributeAccessIssue] - columns=data_table_state.columns, # pyright: ignore[reportAttributeAccessIssue] + data=data_table_state.data, # ty:ignore[unresolved-attribute] + columns=data_table_state.columns, # ty:ignore[unresolved-attribute] ) else: - data_table_component = DataTable.create(data=data_table_state.data) # pyright: ignore[reportAttributeAccessIssue] + data_table_component = DataTable.create(data=data_table_state.data) # ty:ignore[unresolved-attribute] data_table_dict = data_table_component.render() @@ -127,7 +127,7 @@ def test_serialize_dataframe(): """Test if dataframe is serialized correctly.""" simple_dataframe = pd.DataFrame( [["foo", "bar"], ["foo1", "bar1"]], - columns=["column1", "column2"], # pyright: ignore [reportArgumentType] + columns=["column1", "column2"], ) value = serialize(simple_dataframe) assert value == serialize_dataframe(simple_dataframe) diff --git a/tests/units/components/datadisplay/test_shiki_code.py b/tests/units/components/datadisplay/test_shiki_code.py index b405127ee5e..4a44fb0f917 100644 --- a/tests/units/components/datadisplay/test_shiki_code.py +++ b/tests/units/components/datadisplay/test_shiki_code.py @@ -95,7 +95,7 @@ def test_create_shiki_code_block( # Test that the first child is the code code_block_component = component.children[0] - assert code_block_component.code._var_value == expected_first_child # pyright: ignore [reportAttributeAccessIssue] + assert code_block_component.code._var_value == expected_first_child # ty:ignore[unresolved-attribute] applied_styles = component.style for key, value in expected_styles.items(): @@ -130,12 +130,12 @@ def test_create_shiki_high_level_code_block( # Test that the first child is the code block component code_block_component = component.children[0] - assert code_block_component.code._var_value == children[0] # pyright: ignore [reportAttributeAccessIssue] + assert code_block_component.code._var_value == children[0] # ty:ignore[unresolved-attribute] # Check if the transformer is set correctly if expected if expected_transformers: exp_trans_names = [t.__name__ for t in expected_transformers] - for transformer in code_block_component.transformers._var_value: # pyright: ignore [reportAttributeAccessIssue] + for transformer in code_block_component.transformers._var_value: # ty:ignore[unresolved-attribute] assert type(transformer).__name__ in exp_trans_names # Check if the second child is the copy button if can_copy is True @@ -163,12 +163,12 @@ def test_shiki_high_level_code_block_theme_language_mapping(children, props): if "theme" in props: assert component.children[ 0 - ].theme._var_value == ShikiHighLevelCodeBlock._map_themes(props["theme"]) # pyright: ignore [reportAttributeAccessIssue] + ].theme._var_value == ShikiHighLevelCodeBlock._map_themes(props["theme"]) # ty:ignore[unresolved-attribute] # Test that the language is mapped correctly if "language" in props: assert component.children[ 0 - ].language._var_value == ShikiHighLevelCodeBlock._map_languages( # pyright: ignore [reportAttributeAccessIssue] + ].language._var_value == ShikiHighLevelCodeBlock._map_languages( # ty:ignore[unresolved-attribute] props["language"] ) diff --git a/tests/units/components/forms/test_form.py b/tests/units/components/forms/test_form.py index 160be7681f9..592653bb008 100644 --- a/tests/units/components/forms/test_form.py +++ b/tests/units/components/forms/test_form.py @@ -17,7 +17,7 @@ def test_render_on_submit(): _var_type=EventChain, ) f = Form.create(on_submit=submit_it) - exp_submit_name = f"handleSubmit_{f.handle_submit_unique_name}" # pyright: ignore [reportAttributeAccessIssue] + exp_submit_name = f"handleSubmit_{f.handle_submit_unique_name}" # ty:ignore[unresolved-attribute] assert f"onSubmit:{exp_submit_name}" in f.render()["props"] diff --git a/tests/units/components/media/test_image.py b/tests/units/components/media/test_image.py index 9692c3b99f8..2585ee8eb11 100644 --- a/tests/units/components/media/test_image.py +++ b/tests/units/components/media/test_image.py @@ -16,7 +16,7 @@ def pil_image() -> Img: """ rng = np.random.default_rng() imarray = rng.random((100, 100, 3)) * 255 - return PIL.Image.fromarray(imarray.astype("uint8")).convert("RGBA") # pyright: ignore [reportAttributeAccessIssue] + return PIL.Image.fromarray(imarray.astype("uint8")).convert("RGBA") # ty:ignore[possibly-missing-submodule] def test_serialize_image(pil_image: Img): @@ -34,4 +34,4 @@ def test_serialize_image(pil_image: Img): def test_set_src_str(): """Test that setting the src works.""" image = rx.image(src="pic2.jpeg") - assert str(image.src) == '"pic2.jpeg"' # pyright: ignore [reportAttributeAccessIssue] + assert str(image.src) == '"pic2.jpeg"' # ty:ignore[unresolved-attribute] diff --git a/tests/units/components/test_component.py b/tests/units/components/test_component.py index 293132190c2..b4964626e6f 100644 --- a/tests/units/components/test_component.py +++ b/tests/units/components/test_component.py @@ -43,8 +43,8 @@ import reflex as rx from reflex import ( - _COMPONENTS_BASE_MAPPING, # pyright: ignore[reportAttributeAccessIssue] - _COMPONENTS_CORE_MAPPING, # pyright: ignore[reportAttributeAccessIssue] + _COMPONENTS_BASE_MAPPING, # ty:ignore[unresolved-import] + _COMPONENTS_CORE_MAPPING, # ty:ignore[unresolved-import] ) from reflex.compiler.utils import compile_custom_component from reflex.state import BaseState @@ -868,7 +868,7 @@ def test_create_custom_component(my_component): """ component = rx.memo(my_component)(prop1="test", prop2=1) assert component.tag == "MyComponent" - assert set(component.get_props()) == {"prop1", "prop2"} + assert set(component.get_props()) == {"prop1", "prop2"} # ty:ignore[missing-argument] assert component.tag in CUSTOM_COMPONENTS @@ -1245,7 +1245,8 @@ class EventState(rx.State): def handler(self): """A handler that does nothing.""" - def handler2(self, arg): + @rx.event + def handler2(self, arg: int): """A handler that takes an arg. Args: @@ -1368,17 +1369,17 @@ def handler2(self, arg): id="direct-event-handler", ), pytest.param( - rx.fragment(on_blur=EventState.handler2(TEST_VAR)), # pyright: ignore [reportCallIssue] + rx.fragment(on_blur=EventState.handler2(TEST_VAR)), [ARG_VAR, TEST_VAR], id="direct-event-handler-arg", ), pytest.param( - rx.fragment(on_blur=EventState.handler2(EventState.v)), # pyright: ignore [reportCallIssue] + rx.fragment(on_blur=EventState.handler2(EventState.v)), [ARG_VAR, EventState.v], id="direct-event-handler-arg2", ), pytest.param( - rx.fragment(on_blur=lambda: EventState.handler2(TEST_VAR)), # pyright: ignore [reportCallIssue] + rx.fragment(on_blur=lambda: EventState.handler2(TEST_VAR)), [ARG_VAR, TEST_VAR], id="direct-event-handler-lambda", ), @@ -1684,7 +1685,8 @@ def test_validate_invalid_children(): rx.fragment(invalid_component()), rx.fragment( rx.foreach( - LiteralVar.create([1, 2, 3]), lambda x: invalid_component(x) + LiteralVar.create([1, 2, 3]), + lambda x: invalid_component(x), ) ), ) @@ -1868,7 +1870,7 @@ def get_event_triggers(cls) -> dict[str, Any]: ) def test_component_add_imports(tags): class BaseComponent(Component): - def _get_imports(self) -> ImportDict: # pyright: ignore [reportIncompatibleMethodOverride] + def _get_imports(self) -> ImportDict: return {} class Reference(Component): @@ -1880,7 +1882,7 @@ def _get_imports(self) -> ParsedImportDict: ) class TestBase(Component): - def add_imports( # pyright: ignore [reportIncompatibleMethodOverride] + def add_imports( self, ) -> dict[str, str | ImportVar | list[str] | list[ImportVar]]: return {"foo": "bar"} @@ -1910,7 +1912,7 @@ class ChildComponent1(BaseComponent): pass class GrandchildComponent1(ChildComponent1): - def add_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] + def add_hooks(self): return [ "const hook2 = 43", "const hook3 = 44", @@ -1923,11 +1925,11 @@ def add_hooks(self): ] class GrandchildComponent2(ChildComponent1): - def _get_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] + def _get_hooks(self): return "const hook5 = 46" class GreatGrandchildComponent2(GrandchildComponent2): - def add_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] + def add_hooks(self): return [ "const hook2 = 43", "const hook6 = 47", @@ -2002,7 +2004,7 @@ def add_custom_code(self): ] class GrandchildComponent2(ChildComponent1): - def _get_custom_code(self): # pyright: ignore [reportIncompatibleMethodOverride] + def _get_custom_code(self): return "const custom_code5 = 46" class GreatGrandchildComponent2(GrandchildComponent2): @@ -2120,7 +2122,7 @@ def add_style(self): class StyledComponent(ParentComponent): tag = "StyledComponent" - def add_style(self): # pyright: ignore [reportIncompatibleMethodOverride] + def add_style(self): return { "color": v1, "fake": v2, diff --git a/tests/units/components/test_props.py b/tests/units/components/test_props.py index e14f1e05158..772dbf863bd 100644 --- a/tests/units/components/test_props.py +++ b/tests/units/components/test_props.py @@ -206,8 +206,8 @@ def handle_input(self, value: str): pass props = EventProps( - on_click=FooState.handle_click, # pyright: ignore[reportArgumentType] - not_start_with_on=FooState.handle_input, # pyright: ignore[reportArgumentType] + on_click=FooState.handle_click, + not_start_with_on=FooState.handle_input, ) props_dict = props.dict() assert isinstance(props_dict["onClick"], EventChain) diff --git a/tests/units/components/typography/test_markdown.py b/tests/units/components/typography/test_markdown.py index 2ddc591252b..780713121f1 100644 --- a/tests/units/components/typography/test_markdown.py +++ b/tests/units/components/typography/test_markdown.py @@ -29,7 +29,7 @@ def test_get_component(tag, expected): expected: The expected component. """ md = Markdown.create("# Hello") - assert tag in md.component_map # pyright: ignore [reportAttributeAccessIssue] + assert tag in md.component_map # ty:ignore[unresolved-attribute] assert md.get_component(tag).tag == expected diff --git a/tests/units/conftest.py b/tests/units/conftest.py index 36baee0ec8e..a5eb3ad31d5 100644 --- a/tests/units/conftest.py +++ b/tests/units/conftest.py @@ -92,7 +92,7 @@ def upload_sub_state_event_spec(): Returns: Event Spec. """ - return EventSpec(handler=SubUploadState.handle_upload, upload=True) # pyright: ignore [reportCallIssue] + return EventSpec(handler=SubUploadState.handle_upload, upload=True) # ty:ignore[invalid-argument-type, unknown-argument] @pytest.fixture @@ -102,7 +102,7 @@ def upload_event_spec(): Returns: Event Spec. """ - return EventSpec(handler=UploadState.handle_upload1, upload=True) # pyright: ignore [reportCallIssue] + return EventSpec(handler=UploadState.handle_upload1, upload=True) # ty:ignore[invalid-argument-type, unknown-argument] @pytest.fixture diff --git a/tests/units/docgen/test_class_and_component.py b/tests/units/docgen/test_class_and_component.py index 215f6875793..3bc7a458389 100644 --- a/tests/units/docgen/test_class_and_component.py +++ b/tests/units/docgen/test_class_and_component.py @@ -315,7 +315,7 @@ class _DataclassWithFieldDoc: name: From docstring. """ - name: str = dataclasses.field(default="x", doc="From field.doc") + name: str = dataclasses.field(default="x", doc="From field.doc") # ty:ignore[no-matching-overload] doc = generate_class_documentation(_DataclassWithFieldDoc) fields_by_name = {f.name: f for f in doc.fields} diff --git a/tests/units/experimental/test_memo.py b/tests/units/experimental/test_memo.py index efb006d545d..835047cd0a9 100644 --- a/tests/units/experimental/test_memo.py +++ b/tests/units/experimental/test_memo.py @@ -514,7 +514,7 @@ class RestrictedChild(Component): @rx._x.memo def transparent(children: rx.Var[rx.Component]) -> rx.Component: - return children # type: ignore[return-value] + return children # type: ignore[return-value] # ty:ignore[invalid-return-type] wrapped_child = transparent(RestrictedChild.create()) parent = ValidParent.create(wrapped_child) diff --git a/tests/units/istate/manager/test_expiration.py b/tests/units/istate/manager/test_expiration.py index f20ea71b052..81462c868e2 100644 --- a/tests/units/istate/manager/test_expiration.py +++ b/tests/units/istate/manager/test_expiration.py @@ -59,8 +59,8 @@ async def test_memory_state_manager_evicts_expired_state( """Expired states should be removed from the in-memory cache and locks.""" state_token = BaseStateToken(ident=token, cls=ExpiringState) - async with state_manager_memory.modify_state(state_token) as state: - state.value = 42 + async with state_manager_memory.modify_state(state_token) as state: # ty:ignore[invalid-argument-type] + state.value = 42 # ty:ignore[unresolved-attribute] assert token in state_manager_memory.states assert token in state_manager_memory._states_locks @@ -91,7 +91,7 @@ async def test_memory_state_manager_get_state_refreshes_expiration( same_state = await state_manager_memory.get_state(state_token) assert same_state is state - assert state_manager_memory._token_expires_at[token] > expires_at + assert state_manager_memory._token_expires_at[token][0] > expires_at[0] await asyncio.sleep(0.6) @@ -116,7 +116,7 @@ async def test_memory_state_manager_set_state_refreshes_expiration( await state_manager_memory.set_state(state_token, state) - assert state_manager_memory._token_expires_at[token] > expires_at + assert state_manager_memory._token_expires_at[token][0] > expires_at[0] await asyncio.sleep(0.6) @@ -139,7 +139,7 @@ async def test_memory_state_manager_multiple_accesses_extend_expiration( for _ in range(3): await asyncio.sleep(0.25) assert await state_manager_memory.get_state(state_token) is state - assert state_manager_memory._token_expires_at[token] > expires_at + assert state_manager_memory._token_expires_at[token][0] > expires_at[0] expires_at = state_manager_memory._token_expires_at[token] await asyncio.sleep(0.6) @@ -196,13 +196,13 @@ async def test_memory_state_manager_refreshes_expiration_after_locked_access( """Releasing a long-held state should start a fresh expiration window.""" state_token = BaseStateToken(ident=token, cls=ExpiringState) - async with state_manager_memory.modify_state(state_token) as state: - state.value = 5 + async with state_manager_memory.modify_state(state_token) as state: # ty:ignore[invalid-argument-type] + state.value = 5 # ty:ignore[unresolved-attribute] expires_at = state_manager_memory._token_expires_at[token] await asyncio.sleep(1.2) assert token in state_manager_memory.states - assert state_manager_memory._token_expires_at[token] > expires_at + assert state_manager_memory._token_expires_at[token][0] > expires_at[0] await asyncio.sleep(0.6) diff --git a/tests/units/istate/manager/test_redis.py b/tests/units/istate/manager/test_redis.py index 0b37389a337..bca09046aea 100644 --- a/tests/units/istate/manager/test_redis.py +++ b/tests/units/istate/manager/test_redis.py @@ -71,7 +71,7 @@ def event_log(state_manager_redis: StateManagerRedis) -> list[dict[str, Any]]: Returns: The redis event log. """ - return state_manager_redis.redis._internals["event_log"] # pyright: ignore[reportAttributeAccessIssue] + return state_manager_redis.redis._internals["event_log"] # ty:ignore[unresolved-attribute] @pytest.fixture @@ -87,7 +87,7 @@ def event_log_on_update(state_manager_redis: StateManagerRedis) -> asyncio.Event Returns: The event that is set when new events are added to the redis event log. """ - return state_manager_redis.redis._internals["event_log_on_update"] # pyright: ignore[reportAttributeAccessIssue] + return state_manager_redis.redis._internals["event_log_on_update"] # ty:ignore[unresolved-attribute] @pytest.mark.asyncio @@ -131,13 +131,13 @@ async def test_modify( # Initial modify should set count to 1 async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state) + BaseStateToken(ident=token, cls=root_state) # ty:ignore[invalid-argument-type] ) as new_state: - new_state.count = 1 + new_state.count = 1 # ty:ignore[unresolved-attribute] # Subsequent modify should set count to 2 async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state) + BaseStateToken(ident=token, cls=root_state) # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) assert new_state.count == 1 @@ -178,9 +178,9 @@ async def test_modify_oplock( # Initial modify should set count to 1 async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: - new_state.count = 1 + new_state.count = 1 # ty:ignore[unresolved-attribute] # Initial state manager should be holding a lease lease_task_1 = state_manager_redis._local_leases.get(token) @@ -202,9 +202,9 @@ async def test_modify_oplock( # The second modify should NOT trigger another redis lock async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: - new_state.count = 2 + new_state.count = 2 # ty:ignore[unresolved-attribute] assert state_lock_1.locked() lock_events_after = len([ @@ -218,9 +218,9 @@ async def test_modify_oplock( # Contend the lock from another state manager event_log_on_update.clear() async with state_manager_2.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: - new_state.count = 3 + new_state.count = 3 # ty:ignore[unresolved-attribute] state_lock_2 = state_manager_2._cached_states_locks.get(token) assert state_lock_2 is not None assert state_lock_2.locked() @@ -315,7 +315,7 @@ async def test_oplock_contention_queue( async def modify_1(): async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -326,7 +326,7 @@ async def modify_2(): await modify_started.wait() modify_2_started.set() async with state_manager_2.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -336,7 +336,7 @@ async def modify_3(): await modify_started.wait() modify_2_started.set() async with state_manager_2.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -414,7 +414,7 @@ async def test_oplock_contention_no_lease( async def modify_1(): async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -425,7 +425,7 @@ async def modify_2(): await modify_started.wait() modify_2_started.set() async with state_manager_2.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -435,7 +435,7 @@ async def modify_3(): await modify_started.wait() modify_2_started.set() async with state_manager_3.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 @@ -514,7 +514,7 @@ async def test_oplock_contention_racers( async def modify_1(): nonlocal lease_1 async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: lease_1 = await state_manager_redis._get_local_lease(token) assert isinstance(new_state, root_state) @@ -525,7 +525,7 @@ async def modify_2(): await asyncio.sleep(racer_delay) nonlocal lease_2 async with state_manager_2.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: lease_2 = await state_manager_2._get_local_lease(token) assert isinstance(new_state, root_state) @@ -574,7 +574,7 @@ async def canceller(): task = asyncio.create_task(canceller()) async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert await state_manager_redis._get_local_lease(token) is None assert isinstance(new_state, root_state) @@ -602,24 +602,24 @@ async def test_oplock_fetch_substate( state_manager_redis._oplock_enabled = True async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=SubState1), + BaseStateToken(ident=token, cls=SubState1), # ty:ignore[invalid-argument-type] ) as new_state: - assert SubState1.get_name() in new_state.substates - assert SubState2.get_name() not in new_state.substates + assert SubState1.get_name() in new_state.substates # ty:ignore[unresolved-attribute] + assert SubState2.get_name() not in new_state.substates # ty:ignore[unresolved-attribute] async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=SubState2), + BaseStateToken(ident=token, cls=SubState2), # ty:ignore[invalid-argument-type] ) as new_state: # Both substates should be fetched and cached. - assert SubState1.get_name() in new_state.substates - assert SubState2.get_name() in new_state.substates + assert SubState1.get_name() in new_state.substates # ty:ignore[unresolved-attribute] + assert SubState2.get_name() in new_state.substates # ty:ignore[unresolved-attribute] async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=SubState1), + BaseStateToken(ident=token, cls=SubState1), # ty:ignore[invalid-argument-type] ) as new_state: # Both substates should be fetched and cached now. - assert SubState1.get_name() in new_state.substates - assert SubState2.get_name() in new_state.substates + assert SubState1.get_name() in new_state.substates # ty:ignore[unresolved-attribute] + assert SubState2.get_name() in new_state.substates # ty:ignore[unresolved-attribute] # Should have still only been one lock acquisition. lock_events = len([ @@ -677,7 +677,7 @@ async def test_oplock_hold_oplock_after_cancel( async def modify(): async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: modify_started.set() assert isinstance(new_state, root_state) @@ -714,7 +714,7 @@ async def modify(): # Modify the state again, this should get a new lock and lease event_log_on_update.clear() async with state_manager_redis.modify_state( - BaseStateToken(ident=token, cls=root_state), + BaseStateToken(ident=token, cls=root_state), # ty:ignore[invalid-argument-type] ) as new_state: assert isinstance(new_state, root_state) new_state.count += 1 diff --git a/tests/units/reflex_base/event/processor/test_event_processor.py b/tests/units/reflex_base/event/processor/test_event_processor.py index bcc1108be98..5029f1fb6ce 100644 --- a/tests/units/reflex_base/event/processor/test_event_processor.py +++ b/tests/units/reflex_base/event/processor/test_event_processor.py @@ -124,7 +124,7 @@ async def _background_slow_logging_handler(value: str = "default"): _CALL_LOG.append({"value": value}) -_background_slow_logging_handler._reflex_background_task = True # type: ignore[attr-defined] +_background_slow_logging_handler._reflex_background_task = True # type: ignore[attr-defined] # ty:ignore[unresolved-attribute] noop_event = EventHandler(fn=_noop_handler) diff --git a/tests/units/reflex_base/utils/pyi_generator/dataset/classvar_and_private.py b/tests/units/reflex_base/utils/pyi_generator/dataset/classvar_and_private.py index e9aa27b9243..b7ee8e9f0dc 100644 --- a/tests/units/reflex_base/utils/pyi_generator/dataset/classvar_and_private.py +++ b/tests/units/reflex_base/utils/pyi_generator/dataset/classvar_and_private.py @@ -30,7 +30,7 @@ class StrictComponent(Component): _valid_children: ClassVar[list[str]] = ["ChildA", "ChildB"] # The memoization mode. - _memoization_mode: ClassVar[Any] = None + _memoization_mode: ClassVar[Any] = None # ty:ignore[invalid-attribute-override] # A public prop that should appear in create(). visible_prop: Var[str] = field(doc="A prop visible in the stub.") diff --git a/tests/units/reflex_base/utils/pyi_generator/dataset/staticmethod_namespace.py b/tests/units/reflex_base/utils/pyi_generator/dataset/staticmethod_namespace.py index 3f5fc00f725..380b534009c 100644 --- a/tests/units/reflex_base/utils/pyi_generator/dataset/staticmethod_namespace.py +++ b/tests/units/reflex_base/utils/pyi_generator/dataset/staticmethod_namespace.py @@ -29,7 +29,7 @@ def send_notification(message: str, level: str = "info") -> EventSpec: Returns: The event spec. """ - return EventSpec() # type: ignore[call-arg] + return EventSpec() # type: ignore[call-arg] # ty:ignore[missing-argument] class Notify(ComponentNamespace): diff --git a/tests/units/reflex_cli/v2/test_apps.py b/tests/units/reflex_cli/v2/test_apps.py index 218068dc8f0..84d48c41a7e 100644 --- a/tests/units/reflex_cli/v2/test_apps.py +++ b/tests/units/reflex_cli/v2/test_apps.py @@ -15,7 +15,7 @@ hosting_cli = ( get_command(hosting_cli) if isinstance(hosting_cli, Typer) else hosting_cli -) +) # ty:ignore[invalid-assignment] runner = CliRunner() diff --git a/tests/units/reflex_cli/v2/test_gcp.py b/tests/units/reflex_cli/v2/test_gcp.py index 8109504133f..5bbf63986d4 100644 --- a/tests/units/reflex_cli/v2/test_gcp.py +++ b/tests/units/reflex_cli/v2/test_gcp.py @@ -9,11 +9,11 @@ from click.testing import CliRunner from pytest_mock import MockFixture from reflex_cli.utils import hosting -from reflex_cli.v2.deployments import hosting_cli +from reflex_cli.v2.deployments import hosting_cli as _hosting_cli from typer.main import Typer, get_command hosting_cli = ( - get_command(hosting_cli) if isinstance(hosting_cli, Typer) else hosting_cli + get_command(_hosting_cli) if isinstance(_hosting_cli, Typer) else _hosting_cli ) runner = CliRunner() diff --git a/tests/units/reflex_cli/v2/test_project.py b/tests/units/reflex_cli/v2/test_project.py index 81e494cade0..343232d49f8 100644 --- a/tests/units/reflex_cli/v2/test_project.py +++ b/tests/units/reflex_cli/v2/test_project.py @@ -11,7 +11,7 @@ hosting_cli = ( get_command(hosting_cli) if isinstance(hosting_cli, Typer) else hosting_cli -) +) # ty:ignore[invalid-assignment] runner = CliRunner() diff --git a/tests/units/reflex_cli/v2/test_secrets.py b/tests/units/reflex_cli/v2/test_secrets.py index 0ee199b698f..a9e4263a1b2 100644 --- a/tests/units/reflex_cli/v2/test_secrets.py +++ b/tests/units/reflex_cli/v2/test_secrets.py @@ -10,7 +10,7 @@ hosting_cli = ( get_command(hosting_cli) if isinstance(hosting_cli, Typer) else hosting_cli -) +) # ty:ignore[invalid-assignment] runner = CliRunner() diff --git a/tests/units/reflex_cli/v2/test_vmtypes_regions.py b/tests/units/reflex_cli/v2/test_vmtypes_regions.py index b3231cc84ef..8bdcccb71d0 100644 --- a/tests/units/reflex_cli/v2/test_vmtypes_regions.py +++ b/tests/units/reflex_cli/v2/test_vmtypes_regions.py @@ -10,7 +10,7 @@ hosting_cli = ( get_command(hosting_cli) if isinstance(hosting_cli, Typer) else hosting_cli -) +) # ty:ignore[invalid-assignment] runner = CliRunner() diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 887f6a3d8b4..c4ef9ada033 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -190,16 +190,16 @@ class TestAuthProvider(AuthProvider): login_path: str = "/login" logout_path: str = "/logout" - def login(self): # pyright: ignore [reportIncompatibleMethodOverride] + def login(self): """Login.""" - def is_authenticated(self): # pyright: ignore [reportIncompatibleMethodOverride] + def is_authenticated(self): """Is authenticated.""" - def get_admin_user(self): # pyright: ignore [reportIncompatibleMethodOverride] + def get_admin_user(self): """Get admin user.""" - def logout(self): # pyright: ignore [reportIncompatibleMethodOverride] + def logout(self): """Logout.""" return TestAuthProvider @@ -533,7 +533,7 @@ async def test_dynamic_var_event( clean_registration_context: The registration context fixture, which is cleared before each test. """ clean_registration_context.register_base_state(test_state) - state = test_state() # pyright: ignore [reportCallIssue] + state = test_state() # ty:ignore[missing-argument] state.add_var("int_val", int, 0) def set_int_val(self, value: int): @@ -769,7 +769,7 @@ class DictMutationTestState(BaseState): def add_age(self): """Add an age to the dict.""" - self.details.update({"age": 20}) # pyright: ignore [reportCallIssue, reportArgumentType] + self.details.update({"age": 20}) # ty:ignore[no-matching-overload] def change_name(self): """Change the name in the dict.""" @@ -807,7 +807,7 @@ def add_street_to_home_address(self): def change_friend_name(self): """Change the friend's name in the nested dict.""" - self.friend_in_nested_dict["friend"]["name"] = "Tommy" + self.friend_in_nested_dict["friend"]["name"] = "Tommy" # ty:ignore[invalid-assignment] def remove_friend(self): """Remove the friend from the nested dict.""" @@ -815,7 +815,7 @@ def remove_friend(self): def add_friend_age(self): """Add an age to the friend in the nested dict.""" - self.friend_in_nested_dict["friend"]["age"] = 30 + self.friend_in_nested_dict["friend"]["age"] = 30 # ty:ignore[invalid-assignment] return DictMutationTestState() @@ -1091,7 +1091,7 @@ async def test_upload_file_keeps_form_open_until_stream_completes( form_data = FormData([("files", file1), ("files", file2)]) original_close = form_data.close form_close = AsyncMock(side_effect=original_close) - form_data.close = form_close + form_data.close = form_close # ty:ignore[invalid-assignment] async def form(): # noqa: RUF029 return form_data @@ -1201,7 +1201,7 @@ async def test_upload_file_closes_form_on_form_error( form_data = FormData([("files", file1)]) original_close = form_data.close form_close = AsyncMock(side_effect=original_close) - form_data.close = form_close + form_data.close = form_close # ty:ignore[invalid-assignment] async def cancelled_form(): await asyncio.sleep(0) @@ -1237,7 +1237,7 @@ async def test_upload_file_closes_form_on_event_creation_cancellation( form_data = FormData([("files", file1)]) original_close = form_data.close form_close = AsyncMock(side_effect=original_close) - form_data.close = form_close + form_data.close = form_close # ty:ignore[invalid-assignment] async def form(): # noqa: RUF029 return form_data @@ -1246,7 +1246,7 @@ async def form(): # noqa: RUF029 # Patch getlist on the form_data to raise CancelledError during event # creation (after form is parsed, before streaming begins). - form_data.getlist = Mock(side_effect=asyncio.CancelledError) + form_data.getlist = Mock(side_effect=asyncio.CancelledError) # ty:ignore[invalid-assignment] upload_fn = upload(app) with pytest.raises(asyncio.CancelledError): @@ -1284,7 +1284,7 @@ async def test_upload_file_closes_form_if_response_cancelled_before_stream_start form_data = FormData([("files", file1)]) original_close = form_data.close form_close = AsyncMock(side_effect=original_close) - form_data.close = form_close + form_data.close = form_close # ty:ignore[invalid-assignment] async def form(): # noqa: RUF029 return form_data @@ -1337,7 +1337,7 @@ async def test_upload_file_raises_client_disconnect_when_stream_send_fails( form_data = FormData([("files", file1)]) original_close = form_data.close form_close = AsyncMock(side_effect=original_close) - form_data.close = form_close + form_data.close = form_close # ty:ignore[invalid-assignment] async def form(): # noqa: RUF029 return form_data @@ -1753,7 +1753,7 @@ def comp_dynamic(self) -> str: Returns: same as self.dynamic """ - return self.dynamic # pyright: ignore[reportAttributeAccessIssue] + return self.dynamic # ty:ignore[unresolved-attribute] def test_dynamic_arg_shadow( @@ -1805,7 +1805,7 @@ def cleanup_dynamic_arg(): """Fixture to reset DynamicState class vars after each test.""" yield with contextlib.suppress(AttributeError): - del State.dynamic # pyright: ignore[reportAttributeAccessIssue] + del State.dynamic # ty:ignore[unresolved-attribute] State.computed_vars.pop("dynamic", None) State.vars.pop("dynamic", None) @@ -1929,14 +1929,14 @@ def _dynamic_state_event(name, val, **kwargs): if isinstance(app.state_manager, StateManagerRedis): # When redis is used, the state is not updated until the processing is complete state = await app.state_manager.get_state(substate_token) - assert state.dynamic == prev_exp_val # pyright: ignore[reportAttributeAccessIssue] + assert state.dynamic == prev_exp_val # ty:ignore[unresolved-attribute] if environment.REFLEX_OPLOCK_ENABLED.get(): await app.state_manager.close() # check that router data was written to the state_manager store state = await app.state_manager.get_state(substate_token) - assert state.dynamic == exp_val # pyright: ignore[reportAttributeAccessIssue] + assert state.dynamic == exp_val # ty:ignore[unresolved-attribute] # a simple state update event should NOT trigger on_load or route var side effects emitted_deltas.clear() @@ -2047,7 +2047,7 @@ def compilable_app(tmp_path: Path) -> Generator[tuple[App, Path], None, None]: """, ) app = App(theme=None) - app._get_frontend_packages = unittest.mock.Mock() + app._get_frontend_packages = unittest.mock.Mock() # ty:ignore[invalid-assignment] with chdir(app_path): yield app, web_dir @@ -2308,19 +2308,19 @@ def test_app_wrap_priority( class Fragment1(Component): tag = "Fragment1" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: return {(99, "Box"): rx.box()} class Fragment2(Component): tag = "Fragment2" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: return {(50, "Text"): rx.text()} class Fragment3(Component): tag = "Fragment3" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: return {(10, "Fragment2"): Fragment2.create()} def page(): @@ -2448,7 +2448,7 @@ def test_raise_on_state(): def test_call_app(): """Test that the app can be called.""" app = App() - app._compile = unittest.mock.Mock() + app._compile = unittest.mock.Mock() # ty:ignore[invalid-assignment] api = app() assert isinstance(api, Starlette) diff --git a/tests/units/test_config.py b/tests/units/test_config.py index b955f00f904..061b4903a3d 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -25,7 +25,7 @@ def test_requires_app_name(): """Test that a config requires an app_name.""" with pytest.raises(TypeError): - rx.Config() # pyright: ignore[reportCallIssue] + rx.Config() # ty:ignore[missing-argument] def test_set_app_name(base_config_values): @@ -366,7 +366,7 @@ def test_replace_defaults( exp_config_values: The expected config values. """ mock_os_env = os.environ.copy() - monkeypatch.setattr(reflex_base.config.os, "environ", mock_os_env) # pyright: ignore[reportPrivateImportUsage] + monkeypatch.setattr(reflex_base.config.os, "environ", mock_os_env) mock_os_env.update({k: str(v) for k, v in env_vars.items()}) c = rx.Config(app_name="a", **config_kwargs) c._set_persistent(**set_persistent_vars) @@ -536,14 +536,14 @@ def test_disable_with_plugin_class(self): def test_disable_with_plugin_instance_backward_compat(self): """Test disabling a plugin by passing an instance (deprecated).""" - config = rx.Config(app_name="test", disable_plugins=[SitemapPlugin()]) # pyright: ignore[reportArgumentType] + config = rx.Config(app_name="test", disable_plugins=[SitemapPlugin()]) # ty:ignore[invalid-argument-type] assert not any(isinstance(p, SitemapPlugin) for p in config.plugins) def test_disable_with_string_backward_compat(self): """Test disabling a plugin by passing a string (deprecated).""" config = rx.Config( app_name="test", - disable_plugins=["reflex.plugins.sitemap.SitemapPlugin"], # pyright: ignore[reportArgumentType] + disable_plugins=["reflex.plugins.sitemap.SitemapPlugin"], # ty:ignore[invalid-argument-type] ) assert not any(isinstance(p, SitemapPlugin) for p in config.plugins) @@ -557,14 +557,14 @@ def test_disable_plugins_normalized_to_classes(self): def test_disable_instance_normalized_to_class(self): """Test that a Plugin instance in disable_plugins is normalized to its class.""" - config = rx.Config(app_name="test", disable_plugins=[SitemapPlugin()]) # pyright: ignore[reportArgumentType] + config = rx.Config(app_name="test", disable_plugins=[SitemapPlugin()]) # ty:ignore[invalid-argument-type] assert config.disable_plugins == [SitemapPlugin] def test_disable_string_normalized_to_class(self): """Test that a string in disable_plugins is normalized to the class.""" config = rx.Config( app_name="test", - disable_plugins=["reflex.plugins.sitemap.SitemapPlugin"], # pyright: ignore[reportArgumentType] + disable_plugins=["reflex.plugins.sitemap.SitemapPlugin"], # ty:ignore[invalid-argument-type] ) assert config.disable_plugins == [SitemapPlugin] @@ -593,7 +593,7 @@ def test_plugins_instance_passthrough(): def test_plugins_class_auto_instantiated(): """A Plugin subclass is auto-instantiated rather than raising deep in the compiler (issue #6440).""" - config = rx.Config(app_name="test", plugins=[SitemapPlugin]) # pyright: ignore[reportArgumentType] + config = rx.Config(app_name="test", plugins=[SitemapPlugin]) # ty:ignore[invalid-argument-type] instances = [p for p in config.plugins if isinstance(p, SitemapPlugin)] assert len(instances) == 1 # And it must be an instance, not the class itself. @@ -603,7 +603,7 @@ def test_plugins_class_auto_instantiated(): def test_plugins_invalid_value_raises_config_error(): """A non-Plugin value raises ConfigError naming the entry, not a deep TypeError (issue #6440).""" with pytest.raises(ConfigError, match=r"reflex\.Config\.plugins"): - rx.Config(app_name="test", plugins=["not-a-plugin"]) # pyright: ignore[reportArgumentType] + rx.Config(app_name="test", plugins=["not-a-plugin"]) # ty:ignore[invalid-argument-type] def test_plugins_class_requiring_args_raises_config_error(): @@ -614,4 +614,4 @@ def __init__(self, required): self.required = required with pytest.raises(ConfigError, match="NeedsArgs"): - rx.Config(app_name="test", plugins=[NeedsArgs]) # pyright: ignore[reportArgumentType] + rx.Config(app_name="test", plugins=[NeedsArgs]) # ty:ignore[invalid-argument-type] diff --git a/tests/units/test_environment.py b/tests/units/test_environment.py index 9164ffe63d9..d8f2c50e758 100644 --- a/tests/units/test_environment.py +++ b/tests/units/test_environment.py @@ -348,7 +348,7 @@ def test_get_with_default(self): def test_set_string_value(self): """Test setting a string value.""" env_var_instance = EnvVar("TEST_VAR", "default", str) - env_var_instance.set("new_value") # type: ignore[arg-type] + env_var_instance.set("new_value") # type: ignore[arg-type] # ty:ignore[invalid-argument-type] assert os.environ.get("TEST_VAR") == "new_value" # Clean up del os.environ["TEST_VAR"] @@ -367,7 +367,7 @@ def test_set_none_value(self, monkeypatch): def test_set_enum_value(self): """Test setting an enum value.""" env_var_instance = EnvVar("TEST_VAR", _TestEnum.VALUE1, _TestEnum) - env_var_instance.set(_TestEnum.VALUE2) # type: ignore[arg-type] + env_var_instance.set(_TestEnum.VALUE2) # type: ignore[arg-type] # ty:ignore[invalid-argument-type] assert os.environ.get("TEST_VAR") == "value2" # Clean up del os.environ["TEST_VAR"] @@ -375,7 +375,7 @@ def test_set_enum_value(self): def test_set_list_value(self): """Test setting a list value.""" env_var_instance = EnvVar("TEST_VAR", [], list[int]) - env_var_instance.set([1, 2, 3]) # type: ignore[arg-type] + env_var_instance.set([1, 2, 3]) # type: ignore[arg-type] # ty:ignore[invalid-argument-type] assert os.environ.get("TEST_VAR") == "1:2:3" # Clean up del os.environ["TEST_VAR"] diff --git a/tests/units/test_event.py b/tests/units/test_event.py index 500dd542097..89566920c11 100644 --- a/tests/units/test_event.py +++ b/tests/units/test_event.py @@ -453,7 +453,7 @@ def handler(self): assert isinstance(handler, EventHandler) assert not handler.event_actions - sp_handler = EventActionState.handler.stop_propagation # pyright: ignore [reportFunctionMemberAccess] + sp_handler = EventActionState.handler.stop_propagation # ty:ignore[unresolved-attribute] assert sp_handler.event_actions == {"stopPropagation": True} # should NOT affect other references to the handler assert not handler.event_actions @@ -615,7 +615,7 @@ def handle_no_actions(self): # Test background + event actions work together bg_temporal_handler = MyTestState.handle_background_temporal assert bg_temporal_handler.event_actions == {"temporal": True} - assert hasattr(bg_temporal_handler.fn, BACKGROUND_TASK_MARKER) # pyright: ignore [reportAttributeAccessIssue] + assert hasattr(bg_temporal_handler.fn, BACKGROUND_TASK_MARKER) # Test no event actions (existing behavior preserved) no_actions_handler = MyTestState.handle_no_actions @@ -690,12 +690,12 @@ async def handle_old_background(self): old_handler = MyTestState.handle_old_style assert isinstance(old_handler, EventHandler) assert old_handler.event_actions == {} - assert not hasattr(old_handler.fn, BACKGROUND_TASK_MARKER) # pyright: ignore [reportAttributeAccessIssue] + assert not hasattr(old_handler.fn, BACKGROUND_TASK_MARKER) # Old background parameter should work unchanged bg_handler = MyTestState.handle_old_background assert bg_handler.event_actions == {} - assert hasattr(bg_handler.fn, BACKGROUND_TASK_MARKER) # pyright: ignore [reportAttributeAccessIssue] + assert hasattr(bg_handler.fn, BACKGROUND_TASK_MARKER) def test_event_var_in_rx_cond(): diff --git a/tests/units/test_health_endpoint.py b/tests/units/test_health_endpoint.py index e86f0589716..a12753a23fc 100644 --- a/tests/units/test_health_endpoint.py +++ b/tests/units/test_health_endpoint.py @@ -66,7 +66,7 @@ async def test_get_redis_status( # Case 2: Database connection error (OperationalError) ( MagicMock(), - sqlalchemy.exc.OperationalError("error", "error", "error"), # pyright: ignore[reportArgumentType] + sqlalchemy.exc.OperationalError("error", "error", "error"), # ty:ignore[invalid-argument-type] {"db": False}, ), ], diff --git a/tests/units/test_model.py b/tests/units/test_model.py index c3d62d94a17..41a2baaee19 100644 --- a/tests/units/test_model.py +++ b/tests/units/test_model.py @@ -105,7 +105,7 @@ def test_automigration( assert versions.exists() # initial table - class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] + class AlembicThing(Model, table=True): t1: str with get_engine().connect() as connection: @@ -122,7 +122,7 @@ class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] model_registry.get_metadata().clear() # Create column t2, mark t1 as optional with default - class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] + class AlembicThing(Model, table=True): t1: str | None = "default" t2: str = "bar" @@ -142,7 +142,7 @@ class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] model_registry.get_metadata().clear() # Drop column t1 - class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] + class AlembicThing(Model, table=True): t2: str = "bar" assert migrate(autogenerate=True) @@ -177,7 +177,7 @@ class AlembicSecond(Model, table=True): # drop table (AlembicSecond) model_registry.get_metadata().clear() - class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] + class AlembicThing(Model, table=True): t2: str = "bar" assert migrate(autogenerate=True) diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index edd3140383e..a3bf1bdbecd 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -1160,7 +1160,7 @@ def test_extract_package_name(): def test_cached_procedure(): call_count = 0 - temp_file = tempfile.mktemp() + temp_file = tempfile.mktemp() # ty:ignore[deprecated] @cached_procedure( cache_file_path=lambda: Path(temp_file), payload_fn=lambda: "constant" diff --git a/tests/units/test_sqlalchemy.py b/tests/units/test_sqlalchemy.py index f344f224a20..8aa14f16bfd 100644 --- a/tests/units/test_sqlalchemy.py +++ b/tests/units/test_sqlalchemy.py @@ -191,7 +191,7 @@ class ModelBase(Base, MappedAsDataclass): id: Mapped[int | None] = mapped_column(primary_key=True, default=None) # initial table - class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] + class AlembicThing(ModelBase): t1: Mapped[str] = mapped_column(default="") with get_engine().connect() as connection: @@ -208,7 +208,7 @@ class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] model_registry.get_metadata().clear() # Create column t2, mark t1 as optional with default - class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] + class AlembicThing(ModelBase): t1: Mapped[str | None] = mapped_column(default="default") t2: Mapped[str] = mapped_column(default="bar") @@ -228,7 +228,7 @@ class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] model_registry.get_metadata().clear() # Drop column t1 - class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] + class AlembicThing(ModelBase): t2: Mapped[str] = mapped_column(default="bar") assert migrate(autogenerate=True) @@ -263,7 +263,7 @@ class AlembicSecond(ModelBase): # drop table (AlembicSecond) model_registry.get_metadata().clear() - class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] + class AlembicThing(ModelBase): t2: Mapped[str] = mapped_column(default="bar") assert migrate(autogenerate=True) diff --git a/tests/units/test_state.py b/tests/units/test_state.py index f793c7af022..b9786f97b01 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -132,7 +132,7 @@ class TestMixin(BaseState, mixin=True): _mixin_backend: rx.Field[int] = rx.field(default_factory=lambda: 10) -class TestState(TestMixin, BaseState): # pyright: ignore[reportUnsafeMultipleInheritance] +class TestState(TestMixin, BaseState): """A test state.""" # Set this class as not test one @@ -297,7 +297,7 @@ def test_state() -> TestState: Returns: A test state. """ - return TestState() # pyright: ignore [reportCallIssue] + return TestState() # ty:ignore[missing-argument] @pytest.fixture @@ -477,13 +477,13 @@ def test_dict(test_state: TestState): def test_class_indexing_with_vars(): """Test that we can index into a state var with another var.""" - prop = TestState.array[TestState.num1] # pyright: ignore [reportCallIssue, reportArgumentType] + prop = TestState.array[TestState.num1] # ty:ignore[invalid-argument-type] assert ( str(prop) == f"{TestState.get_name()}.array{FIELD_MARKER}?.at?.({TestState.get_name()}.num1{FIELD_MARKER})" ) - prop = TestState.mapping["a"][TestState.num1] # pyright: ignore [reportCallIssue, reportArgumentType] + prop = TestState.mapping["a"][TestState.num1] assert ( str(prop) == f'{TestState.get_name()}.mapping{FIELD_MARKER}?.["a"]?.at?.({TestState.get_name()}.num1{FIELD_MARKER})' @@ -603,11 +603,11 @@ def test_get_class_var(): def test_set_class_var(): """Test setting the var of a class.""" with pytest.raises(AttributeError): - TestState.num3 # pyright: ignore [reportAttributeAccessIssue] + TestState.num3 # ty:ignore[unresolved-attribute] TestState._set_var( "num3", Var(_js_expr="num3", _var_type=int)._var_set_state(TestState) ) - var = TestState.num3 # pyright: ignore [reportAttributeAccessIssue] + var = TestState.num3 # ty:ignore[unresolved-attribute] assert var._js_expr == TestState.get_full_name() + ".num3" assert var._var_type is int assert var._var_state == TestState.get_full_name() @@ -1118,22 +1118,22 @@ class DynamicState(BaseState): assert not hasattr(ds1, "dynamic_int") ds1.add_var("dynamic_int", int, 42) # Existing instances get the BaseVar - assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # pyright: ignore [reportAttributeAccessIssue] + assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # ty:ignore[unresolved-attribute] # New instances get an actual value with the default - assert DynamicState().dynamic_int == 42 # pyright: ignore[reportAttributeAccessIssue] + assert DynamicState().dynamic_int == 42 # ty:ignore[unresolved-attribute] ds1.add_var("dynamic_list", list[int], [5, 10]) - assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # pyright: ignore [reportAttributeAccessIssue] + assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # ty:ignore[unresolved-attribute] ds2 = DynamicState() - assert ds2.dynamic_list == [5, 10] # pyright: ignore[reportAttributeAccessIssue] - ds2.dynamic_list.append(15) # pyright: ignore[reportAttributeAccessIssue] - assert ds2.dynamic_list == [5, 10, 15] # pyright: ignore[reportAttributeAccessIssue] - assert DynamicState().dynamic_list == [5, 10] # pyright: ignore[reportAttributeAccessIssue] + assert ds2.dynamic_list == [5, 10] # ty:ignore[unresolved-attribute] + ds2.dynamic_list.append(15) # ty:ignore[unresolved-attribute] + assert ds2.dynamic_list == [5, 10, 15] # ty:ignore[unresolved-attribute] + assert DynamicState().dynamic_list == [5, 10] # ty:ignore[unresolved-attribute] ds1.add_var("dynamic_dict", dict[str, int], {"k1": 5, "k2": 10}) - assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # pyright: ignore [reportAttributeAccessIssue] - assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # pyright: ignore [reportAttributeAccessIssue] - assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10} # pyright: ignore[reportAttributeAccessIssue] + assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # ty:ignore[unresolved-attribute] + assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # ty:ignore[unresolved-attribute] + assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10} # ty:ignore[unresolved-attribute] class InterdependentState(BaseState): @@ -1557,7 +1557,7 @@ def cached_x_side_effect(self) -> int: return counter if use_partial: - HandlerState.handler = functools.partial(HandlerState.handler.fn) # pyright: ignore [reportFunctionMemberAccess] + HandlerState.handler = functools.partial(HandlerState.handler.fn) # ty:ignore[unresolved-attribute] assert isinstance(HandlerState.handler, functools.partial) else: assert isinstance(HandlerState.handler, EventHandler) @@ -2045,11 +2045,11 @@ def loop_exception_handler(loop, context): asyncio.get_event_loop().set_exception_handler(loop_exception_handler) - async with state_manager_redis.modify_state(substate_token_redis): + async with state_manager_redis.modify_state(substate_token_redis): # ty:ignore[invalid-argument-type] await asyncio.sleep(0.01) if environment.REFLEX_OPLOCK_ENABLED.get(): - async with state_manager_redis.modify_state(substate_token_redis): + async with state_manager_redis.modify_state(substate_token_redis): # ty:ignore[invalid-argument-type] await asyncio.sleep(LOCK_EXPIRE_SLEEP) await asyncio.sleep(LOCK_EXPIRE_SLEEP) assert loop_exception is not None @@ -2057,7 +2057,7 @@ def loop_exception_handler(loop, context): raise loop_exception else: with pytest.raises(LockExpiredError): - async with state_manager_redis.modify_state(substate_token_redis): + async with state_manager_redis.modify_state(substate_token_redis): # ty:ignore[invalid-argument-type] await asyncio.sleep(LOCK_EXPIRE_SLEEP) assert loop_exception is None @@ -2100,17 +2100,17 @@ def loop_exception_handler(loop, context): waiter_event = asyncio.Event() async def _coro_blocker(): - async with state_manager_redis.modify_state(substate_token_redis) as state: + async with state_manager_redis.modify_state(substate_token_redis) as state: # ty:ignore[invalid-argument-type] order.append("blocker") waiter_event.set() await asyncio.sleep(LOCK_EXPIRE_SLEEP) - state.num1 = unexp_num1 + state.num1 = unexp_num1 # ty:ignore[unresolved-attribute] async def _coro_waiter(): await waiter_event.wait() - async with state_manager_redis.modify_state(substate_token_redis) as state: + async with state_manager_redis.modify_state(substate_token_redis) as state: # ty:ignore[invalid-argument-type] order.append("waiter") - state.num1 = exp_num1 + state.num1 = exp_num1 # ty:ignore[unresolved-attribute] tasks = [ asyncio.create_task(_coro_blocker()), @@ -2162,7 +2162,7 @@ async def test_state_manager_lock_warning_threshold_contend( order = [] async def _coro_blocker(): - async with state_manager_redis.modify_state(substate_token_redis): + async with state_manager_redis.modify_state(substate_token_redis): # ty:ignore[invalid-argument-type] order.append("blocker") await asyncio.sleep(LOCK_WARN_SLEEP) @@ -2213,7 +2213,7 @@ def mock_app_simple(monkeypatch) -> rx.App: setattr(app_module, CompileVars.APP, app) app._state = TestState - app.event_namespace.emit = CopyingAsyncMock() # pyright: ignore [reportOptionalMemberAccess] + app.event_namespace.emit = CopyingAsyncMock() # ty:ignore[invalid-assignment] def _mock_get_app(*args, **kwargs): return app_module @@ -2819,7 +2819,7 @@ def assert_array_dirty(): assert_array_dirty() mutable_state.array.reverse() assert_array_dirty() - mutable_state.array.sort() # pyright: ignore[reportCallIssue] + mutable_state.array.sort() # ty:ignore[invalid-argument-type] assert_array_dirty() mutable_state.array[0] = 666 assert_array_dirty() @@ -2839,7 +2839,7 @@ def assert_array_dirty(): assert isinstance(mutable_state.array[0], MutableProxy) for item in mutable_state.array: assert isinstance(item, MutableProxy) - item["foo"] = "bar" # pyright: ignore[reportArgumentType, reportCallIssue] + item["foo"] = "bar" assert_array_dirty() @@ -2911,10 +2911,10 @@ def assert_hashmap_dirty(): mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key") assert not isinstance(mutable_value_third_ref, MutableProxy) assert_hashmap_dirty() - mutable_value_third_ref.append("baz") # pyright: ignore[reportAttributeAccessIssue] + mutable_value_third_ref.append("baz") # ty:ignore[unresolved-attribute] assert not mutable_state.dirty_vars # Unfortunately previous refs still will mark the state dirty... nothing doing about that - assert mutable_value.pop() # pyright: ignore[reportCallIssue] + assert mutable_value.pop() assert_hashmap_dirty() @@ -3071,7 +3071,7 @@ def test_duplicate_substate_class(mocker: MockerFixture): class TestState(BaseState): pass - class ChildTestState(TestState): # pyright: ignore [reportRedeclaration] + class ChildTestState(TestState): pass class ChildTestState(TestState): # noqa: F811 @@ -3114,21 +3114,21 @@ class MutableResetState(BaseState): items: list[list[int]] = default instance = MutableResetState() - assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] + assert instance.items.__wrapped__ is not default # ty:ignore[unresolved-attribute] assert instance.items == default == copied_default instance.items.append([3, 3]) assert instance.items != default assert instance.items != copied_default instance.reset() - assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] + assert instance.items.__wrapped__ is not default # ty:ignore[unresolved-attribute] assert instance.items == default == copied_default instance.items.append([3, 3]) assert instance.items != default assert instance.items != copied_default instance.reset() - assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] + assert instance.items.__wrapped__ is not default # ty:ignore[unresolved-attribute] assert instance.items == default == copied_default instance.items.append([3, 3]) assert instance.items != default @@ -3190,31 +3190,29 @@ class UnionState(BaseState): c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo=""))) custom_union: Custom1 | Custom2 | Custom3 = Custom1(foo="") - assert str(UnionState.c3.c2) == f'{UnionState.c3!s}?.["c2"]' # pyright: ignore [reportOptionalMemberAccess] - assert str(UnionState.c3.c2.c1) == f'{UnionState.c3!s}?.["c2"]?.["c1"]' # pyright: ignore [reportOptionalMemberAccess] + assert str(UnionState.c3.c2) == f'{UnionState.c3!s}?.["c2"]' # ty:ignore[unresolved-attribute] + assert str(UnionState.c3.c2.c1) == f'{UnionState.c3!s}?.["c2"]?.["c1"]' # ty:ignore[unresolved-attribute] + assert str(UnionState.c3.c2.c1.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1"]?.["foo"]' # ty:ignore[unresolved-attribute] assert ( - str(UnionState.c3.c2.c1.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1"]?.["foo"]' # pyright: ignore [reportOptionalMemberAccess] + str(UnionState.c3.c2.c1r.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1r"]?.["foo"]' # ty:ignore[unresolved-attribute] ) + assert str(UnionState.c3.c2r.c1) == f'{UnionState.c3!s}?.["c2r"]?.["c1"]' # ty:ignore[unresolved-attribute] assert ( - str(UnionState.c3.c2.c1r.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1r"]?.["foo"]' # pyright: ignore [reportOptionalMemberAccess] + str(UnionState.c3.c2r.c1.foo) == f'{UnionState.c3!s}?.["c2r"]?.["c1"]?.["foo"]' # ty:ignore[unresolved-attribute] ) - assert str(UnionState.c3.c2r.c1) == f'{UnionState.c3!s}?.["c2r"]?.["c1"]' # pyright: ignore [reportOptionalMemberAccess] assert ( - str(UnionState.c3.c2r.c1.foo) == f'{UnionState.c3!s}?.["c2r"]?.["c1"]?.["foo"]' # pyright: ignore [reportOptionalMemberAccess] - ) - assert ( - str(UnionState.c3.c2r.c1r.foo) # pyright: ignore [reportOptionalMemberAccess] + str(UnionState.c3.c2r.c1r.foo) # ty:ignore[unresolved-attribute] == f'{UnionState.c3!s}?.["c2r"]?.["c1r"]?.["foo"]' ) assert str(UnionState.c3i.c2) == f'{UnionState.c3i!s}?.["c2"]' assert str(UnionState.c3r.c2) == f'{UnionState.c3r!s}?.["c2"]' - assert UnionState.custom_union.foo is not None # pyright: ignore [reportAttributeAccessIssue] - assert UnionState.custom_union.c1 is not None # pyright: ignore [reportAttributeAccessIssue] - assert UnionState.custom_union.c1r is not None # pyright: ignore [reportAttributeAccessIssue] - assert UnionState.custom_union.c2 is not None # pyright: ignore [reportAttributeAccessIssue] - assert UnionState.custom_union.c2r is not None # pyright: ignore [reportAttributeAccessIssue] - assert types.is_optional(UnionState.opt_int._var_type) # pyright: ignore [reportAttributeAccessIssue, reportOptionalMemberAccess] - assert types.is_union(UnionState.int_float._var_type) # pyright: ignore [reportAttributeAccessIssue] + assert UnionState.custom_union.foo is not None # ty:ignore[unresolved-attribute] + assert UnionState.custom_union.c1 is not None # ty:ignore[unresolved-attribute] + assert UnionState.custom_union.c1r is not None # ty:ignore[unresolved-attribute] + assert UnionState.custom_union.c2 is not None # ty:ignore[unresolved-attribute] + assert UnionState.custom_union.c2r is not None # ty:ignore[unresolved-attribute] + assert types.is_optional(UnionState.opt_int._var_type) # ty:ignore[unresolved-attribute] + assert types.is_union(UnionState.int_float._var_type) # ty:ignore[unresolved-attribute] def test_set_base_field_via_setter(): @@ -3377,7 +3375,7 @@ def index(): app._compile_page("index") on_load_internal_name = format.format_event_handler( - OnLoadInternalState.on_load_internal # pyright: ignore[reportArgumentType] + OnLoadInternalState.on_load_internal # ty:ignore[invalid-argument-type] ) async with mock_base_state_event_processor as processor: @@ -3441,7 +3439,7 @@ def index(): app._compile_page("index") on_load_internal_name = format.format_event_handler( - OnLoadInternalState.on_load_internal # pyright: ignore[reportArgumentType] + OnLoadInternalState.on_load_internal # ty:ignore[invalid-argument-type] ) async with mock_base_state_event_processor as processor: @@ -3884,9 +3882,9 @@ def test_redis_state_manager_config_knobs(tmp_path, expiration_kwargs, expected_ reflex_base.config.get_config(reload=True) state_manager = StateManagerRedis(redis=mock_redis()) - assert state_manager.lock_expiration == expected_values[0] # pyright: ignore [reportAttributeAccessIssue] - assert state_manager.token_expiration == expected_values[1] # pyright: ignore [reportAttributeAccessIssue] - assert state_manager.lock_warning_threshold == expected_values[2] # pyright: ignore [reportAttributeAccessIssue] + assert state_manager.lock_expiration == expected_values[0] + assert state_manager.token_expiration == expected_values[1] + assert state_manager.lock_warning_threshold == expected_values[2] @pytest.mark.parametrize( @@ -4070,7 +4068,7 @@ def test_mixin_state() -> None: assert "computed" in UsesMixinState.vars assert ( - UsesMixinState(_reflex_internal_init=True)._backend_no_default # pyright: ignore [reportCallIssue] + UsesMixinState(_reflex_internal_init=True)._backend_no_default # ty:ignore[missing-argument, unknown-argument] is not UsesMixinState.backend_vars["_backend_no_default"] ) @@ -4141,7 +4139,7 @@ def test_assignment_to_undeclared_vars(): class State(BaseState): val: str _val: str - __val: str # pyright: ignore [reportGeneralTypeIssues] + __val: str def handle_supported_regular_vars(self): self.val = "no underscore" @@ -4161,8 +4159,8 @@ class Substate(State): def handle_var(self): self.value = 20 - state = State() # pyright: ignore [reportCallIssue] - sub_state = Substate() # pyright: ignore [reportCallIssue] + state = State() # ty:ignore[missing-argument] + sub_state = Substate() # ty:ignore[missing-argument] with pytest.raises(SetUndefinedStateVarError): state.handle_regular_var() @@ -4197,10 +4195,10 @@ class Child(State): bs_token = BaseStateToken(ident=token, cls=Root) dsm = StateManagerDisk() - async with dsm.modify_state(bs_token) as root: - s = await root.get_state(State) + async with dsm.modify_state(bs_token) as root: # ty:ignore[invalid-argument-type] + s = await root.get_state(State) # ty:ignore[unresolved-attribute] s.num += 1 - c = await root.get_state(Child) + c = await root.get_state(Child) # ty:ignore[unresolved-attribute] assert s._get_was_touched() assert not c._get_was_touched() await dsm.close() @@ -4228,7 +4226,7 @@ class DillState(BaseState): _f: Callable | None = None _g: Any = None - state = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] + state = DillState(_reflex_internal_init=True) # ty:ignore[unknown-argument] state._o = Obj(f=lambda: 42) state._f = lambda: 420 @@ -4242,7 +4240,7 @@ class DillState(BaseState): assert unpickled_state._o.f() == 42 # Threading locks are unpicklable normally, and raise TypeError instead of PicklingError. - state2 = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] + state2 = DillState(_reflex_internal_init=True) # ty:ignore[unknown-argument] state2._g = threading.Lock() pk2 = state2._serialize() unpickled_state2 = BaseState._deserialize(pk2) @@ -4250,7 +4248,7 @@ class DillState(BaseState): assert isinstance(unpickled_state2._g, type(threading.Lock())) # Some object, like generator, are still unpicklable with dill. - state3 = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] + state3 = DillState(_reflex_internal_init=True) # ty:ignore[unknown-argument] state3._g = (i for i in range(10)) with pytest.raises(StateSerializationError): @@ -4487,7 +4485,7 @@ def py_Any(self, a: Any): # noqa: D102 assert isinstance(a, list) self.passed = True - def py_unresolvable(self, u: Unresolvable): # noqa: D102, F821 # pyright: ignore [reportUndefinedVariable] + def py_unresolvable(self, u: Unresolvable): # noqa: D102, F821 # ty:ignore[unresolved-reference] assert isinstance(u, list) self.passed = True @@ -4902,7 +4900,7 @@ def __set__(self, instance, value): self._values[id(instance)] = value class DescriptorState(rx.State): - _desc_value: int = _IntDescriptor() # pyright: ignore[reportAssignmentType] + _desc_value: int = _IntDescriptor() # ty:ignore[invalid-assignment] @rx.var def doubled(self) -> int: @@ -4942,14 +4940,14 @@ def __set__(self, instance, value): child_descriptor = _Sentinel("child") class ParentDescState(rx.State): - _shared: int = parent_descriptor # pyright: ignore[reportAssignmentType] + _shared: int = parent_descriptor # ty:ignore[invalid-assignment] @rx.var def parent_view(self) -> int: return self._shared class ChildDescState(ParentDescState): - _shared: int = child_descriptor # pyright: ignore[reportAssignmentType] + _shared: int = child_descriptor # ty:ignore[invalid-assignment] @rx.var def child_view(self) -> int: diff --git a/tests/units/test_telemetry.py b/tests/units/test_telemetry.py index c43a285a192..a6c0447664f 100644 --- a/tests/units/test_telemetry.py +++ b/tests/units/test_telemetry.py @@ -177,7 +177,7 @@ def test_prepare_event_merges_properties(event_defaults): assert event is not None assert event["event"] == "compile" - props: dict = event["properties"] # pyright: ignore[reportAssignmentType] + props: dict = event["properties"] # ty:ignore[invalid-assignment] assert props["pages_count"] == 7 assert props["trigger"] == "initial" # Existing default keys are preserved. @@ -334,5 +334,5 @@ def test_prepare_event_properties_override_kwargs(event_defaults): ) assert event is not None - props: dict = event["properties"] # pyright: ignore[reportAssignmentType] + props: dict = event["properties"] # ty:ignore[invalid-assignment] assert props["template"] == "from-properties" diff --git a/tests/units/test_var.py b/tests/units/test_var.py index 6971cdffcd4..c2c70f99911 100644 --- a/tests/units/test_var.py +++ b/tests/units/test_var.py @@ -1169,7 +1169,7 @@ def test_type_chains(): == '(Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }) ?? {})?.at?.(1)?.at?.(1) - 1)' ) assert ( - str(object_var["c"] + object_var["b"]) # pyright: ignore [reportCallIssue, reportOperatorIssue] + str(object_var["c"] + object_var["b"]) == '(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })?.["c"] + ({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })?.["b"])' ) @@ -1179,7 +1179,7 @@ def test_nested_dict(): assert ( str(arr[0]["bar"][0]) - == '[({ ["bar"] : ["foo", "bar"] })]?.at?.(0)?.["bar"]?.at?.(0)' # pyright: ignore [reportIndexIssue] + == '[({ ["bar"] : ["foo", "bar"] })]?.at?.(0)?.["bar"]?.at?.(0)' ) @@ -1376,7 +1376,7 @@ def test_unsupported_types_for_contains(var: Var): var: The base var. """ with pytest.raises(TypeError) as err: - assert var.contains(1) # pyright: ignore [reportAttributeAccessIssue] + assert var.contains(1) # ty:ignore[unresolved-attribute] assert ( err.value.args[0] == f"Var of type {var._var_type} does not support contains check." @@ -1406,7 +1406,7 @@ def test_unsupported_types_for_string_contains(other): def test_unsupported_default_contains(): with pytest.raises(TypeError) as err: - assert 1 in Var(_js_expr="var", _var_type=str).guess_type() # pyright: ignore [reportOperatorIssue] + assert 1 in Var(_js_expr="var", _var_type=str).guess_type() assert ( err.value.args[0] == "'in' operator not supported for Var types, use Var.contains() instead." diff --git a/tests/units/utils/test_format.py b/tests/units/utils/test_format.py index c7ae6397020..16547cd7fe4 100644 --- a/tests/units/utils/test_format.py +++ b/tests/units/utils/test_format.py @@ -701,7 +701,7 @@ def test_format_query_params(input, output): ("input", "output"), [ ( - TestState(_reflex_internal_init=True).dict(), # pyright: ignore [reportCallIssue] + TestState(_reflex_internal_init=True).dict(), # ty:ignore[missing-argument, unknown-argument] { TestState.get_full_name(): { "array" + FIELD_MARKER: [1, 2, 3.15], @@ -735,7 +735,7 @@ def test_format_query_params(input, output): }, ), ( - DateTimeState(_reflex_internal_init=True).dict(), # pyright: ignore [reportCallIssue] + DateTimeState(_reflex_internal_init=True).dict(), # ty:ignore[unknown-argument] { DateTimeState.get_full_name(): { "d" + FIELD_MARKER: "1989-11-09", diff --git a/tests/units/utils/test_telemetry_accounting.py b/tests/units/utils/test_telemetry_accounting.py index 83103d7f7fb..8f1c80bb0bf 100644 --- a/tests/units/utils/test_telemetry_accounting.py +++ b/tests/units/utils/test_telemetry_accounting.py @@ -162,7 +162,7 @@ def test_collect_compile_event_payload_shape(mocker: MockerFixture): ctx = TelemetryContext(trigger="cli_compile") payload = telemetry_accounting._collect_compile_event_payload( - app, # pyright: ignore[reportArgumentType] + app, ctx, ) @@ -188,7 +188,7 @@ def test_collect_compile_event_payload_with_exception(mocker: MockerFixture): ctx.set_exception(RuntimeError("oops")) payload = telemetry_accounting._collect_compile_event_payload( - app, # pyright: ignore[reportArgumentType] + app, ctx, ) assert payload["exception"] == {"type": "RuntimeError"} @@ -221,7 +221,7 @@ def test_memo_wrapper_class_records_wrapped_component_type(): memo_module = importlib.import_module("reflex.experimental.memo") - wrapper_cls = memo_module._get_experimental_memo_component_class( + wrapper_cls = memo_module._get_experimental_memo_component_class( # ty:ignore[unresolved-attribute] "Button_button_deadbeefcafebabe", Button, ) @@ -237,7 +237,7 @@ class StubMemoWrapper: children = () counts = telemetry_accounting._count_components( - [StubMemoWrapper()], # pyright: ignore[reportArgumentType] + [StubMemoWrapper()], # ty:ignore[invalid-argument-type] ) assert counts == {"Button": 1} @@ -246,7 +246,7 @@ class StubMemoWrapper: def test_collect_features_used_emits_every_known_key(): """All names in ``_KNOWN_FEATURES`` ship in the snapshot, defaulted to 0.""" features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [], ) @@ -265,7 +265,7 @@ class StorageState(BaseState): plain: int = 0 features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [StorageState], ) @@ -290,7 +290,7 @@ class StorageGrandchild(StorageChild): extra: str = Cookie() features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [StorageParent, StorageChild, StorageGrandchild], ) @@ -305,7 +305,7 @@ def test_collect_features_used_upload_reads_class_flag(mocker: MockerFixture): mocker.patch.object(Upload, "is_used", True) used = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [], ) @@ -313,7 +313,7 @@ def test_collect_features_used_upload_reads_class_flag(mocker: MockerFixture): mocker.patch.object(Upload, "is_used", False) unused = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [], ) @@ -330,7 +330,7 @@ class SharedTwo(rx.SharedState): y: int = 0 features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [SharedOne, SharedTwo], ) @@ -348,7 +348,7 @@ def test_collect_features_used_counts_dynamic_routes(): }, ) features = telemetry_accounting._collect_features_used( - app, # pyright: ignore[reportArgumentType] + app, _fake_config(), [], ) @@ -368,7 +368,7 @@ def reflex_internal_task(): app = _fake_app(_lifespan_tasks={user_task: None, reflex_internal_task: None}) features = telemetry_accounting._collect_features_used( - app, # pyright: ignore[reportArgumentType] + app, _fake_config(), [], ) @@ -384,7 +384,7 @@ def test_collect_features_used_counts_registered_db_models(mocker: MockerFixture mocker.patch.object(telemetry_accounting, "ModelRegistry", fake_registry) features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [], ) @@ -394,7 +394,7 @@ def test_collect_features_used_counts_registered_db_models(mocker: MockerFixture def test_collect_features_used_records_state_manager_mode(): """The configured state-manager mode lights up exactly one boolean key.""" features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(state_manager_mode=SimpleNamespace(value="redis")), [], ) @@ -406,7 +406,7 @@ def test_collect_features_used_records_state_manager_mode(): def test_collect_features_used_records_cors_customized(): """A non-default ``cors_allowed_origins`` sets the cors counter to 1.""" features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(cors_allowed_origins=("https://example.com",)), [], ) @@ -416,7 +416,7 @@ def test_collect_features_used_records_cors_customized(): def test_collect_features_used_default_cors_stays_zero(): """Default ``("*",)`` origins read as not customized.""" features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [], ) @@ -436,7 +436,7 @@ def fast(self): """Foreground handler that must not be miscounted.""" features = telemetry_accounting._collect_features_used( - _fake_app(), # pyright: ignore[reportArgumentType] + _fake_app(), _fake_config(), [BgState], ) diff --git a/tests/units/utils/test_token_manager.py b/tests/units/utils/test_token_manager.py index 7e9da751b6c..b73cc0946df 100644 --- a/tests/units/utils/test_token_manager.py +++ b/tests/units/utils/test_token_manager.py @@ -525,7 +525,7 @@ def new_event_namespace() -> EventNamespace: ) event_namespace = EventNamespace(namespace=namespace, app=mock_app) - event_namespace.emit = AsyncMock() + event_namespace.emit = AsyncMock() # ty:ignore[invalid-assignment] created_objs.append(event_namespace) return event_namespace @@ -629,9 +629,9 @@ async def test_redis_token_manager_lost_and_found( event_namespace_factory: Factory fixture for EventNamespace instances. """ event_namespace1 = event_namespace_factory() - emit1_mock: Mock = event_namespace1.emit # pyright: ignore[reportAssignmentType] + emit1_mock: Mock = event_namespace1.emit # ty:ignore[invalid-assignment] event_namespace2 = event_namespace_factory() - emit2_mock: Mock = event_namespace2.emit # pyright: ignore[reportAssignmentType] + emit2_mock: Mock = event_namespace2.emit # ty:ignore[invalid-assignment] await event_namespace1.on_connect(sid="sid1", environ=query_string_for("token1")) await event_namespace2.on_connect(sid="sid2", environ=query_string_for("token2")) @@ -684,9 +684,9 @@ async def test_redis_token_manager_lost_and_found_router_data( event_namespace_factory: Factory fixture for EventNamespace instances. """ event_namespace1 = event_namespace_factory() - emit1_mock: Mock = event_namespace1.emit # pyright: ignore[reportAssignmentType] + emit1_mock: Mock = event_namespace1.emit # ty:ignore[invalid-assignment] event_namespace2 = event_namespace_factory() - emit2_mock: Mock = event_namespace2.emit # pyright: ignore[reportAssignmentType] + emit2_mock: Mock = event_namespace2.emit # ty:ignore[invalid-assignment] await event_namespace1.on_connect(sid="sid1", environ=query_string_for("token1")) await event_namespace2.on_connect(sid="sid2", environ=query_string_for("token2")) diff --git a/tests/units/vars/test_dep_tracking.py b/tests/units/vars/test_dep_tracking.py index 7081fe19f41..838b9593d70 100644 --- a/tests/units/vars/test_dep_tracking.py +++ b/tests/units/vars/test_dep_tracking.py @@ -327,7 +327,7 @@ def test_get_var_value_with_import_from(): async def get_state_import_from(self: DependencyTestState): from tests.units.states.mutation import MutableTestState - return await self.get_var_value(MutableTestState.hashmap) # pyright: ignore[reportArgumentType] + return await self.get_var_value(MutableTestState.hashmap) # ty:ignore[invalid-argument-type] from tests.units.states.mutation import MutableTestState diff --git a/tests/units/vars/test_object.py b/tests/units/vars/test_object.py index c2a479294c3..b61cb4eff9d 100644 --- a/tests/units/vars/test_object.py +++ b/tests/units/vars/test_object.py @@ -139,7 +139,7 @@ def test_typing() -> None: var = ObjectState.base _ = assert_type(var, ObjectVar[Base]) optional_var = ObjectState.base_optional - _ = assert_type(optional_var, ObjectVar[Base]) + _ = assert_type(optional_var, ObjectVar[Base]) # ty:ignore[type-assertion-failure] list_var = ObjectState.base_list _ = assert_type(list_var, ArrayVar[Sequence[Base]]) list_var_0 = list_var[0] @@ -149,7 +149,7 @@ def test_typing() -> None: var = ObjectState.sqlamodel _ = assert_type(var, ObjectVar[SqlaModel]) optional_var = ObjectState.sqlamodel_optional - _ = assert_type(optional_var, ObjectVar[SqlaModel]) + _ = assert_type(optional_var, ObjectVar[SqlaModel]) # ty:ignore[type-assertion-failure] list_var = ObjectState.base_list _ = assert_type(list_var, ArrayVar[Sequence[Base]]) list_var_0 = list_var[0] @@ -159,7 +159,7 @@ def test_typing() -> None: var = ObjectState.dataclass _ = assert_type(var, ObjectVar[Dataclass]) optional_var = ObjectState.dataclass_optional - _ = assert_type(optional_var, ObjectVar[Dataclass]) + _ = assert_type(optional_var, ObjectVar[Dataclass]) # ty:ignore[type-assertion-failure] list_var = ObjectState.base_list _ = assert_type(list_var, ArrayVar[Sequence[Base]]) list_var_0 = list_var[0] diff --git a/uv.lock b/uv.lock index f3122ca7c5b..3de6fc42058 100644 --- a/uv.lock +++ b/uv.lock @@ -3032,19 +3032,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, ] -[[package]] -name = "pyright" -version = "1.1.408" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "nodeenv" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/74/b2/5db700e52554b8f025faa9c3c624c59f1f6c8841ba81ab97641b54322f16/pyright-1.1.408.tar.gz", hash = "sha256:f28f2321f96852fa50b5829ea492f6adb0e6954568d1caa3f3af3a5f555eb684", size = 4400578, upload-time = "2026-01-08T08:07:38.795Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/82/a2c93e32800940d9573fb28c346772a14778b84ba7524e691b324620ab89/pyright-1.1.408-py3-none-any.whl", hash = "sha256:090b32865f4fdb1e0e6cd82bf5618480d48eecd2eb2e70f960982a3d9a4c17c1", size = 6399144, upload-time = "2026-01-08T08:07:37.082Z" }, -] - [[package]] name = "pysocks" version = "1.7.1" @@ -3447,7 +3434,6 @@ dev = [ { name = "psutil" }, { name = "psycopg", extra = ["binary"] }, { name = "pydantic" }, - { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, @@ -3465,6 +3451,7 @@ dev = [ { name = "sqlmodel" }, { name = "starlette-admin" }, { name = "toml" }, + { name = "ty" }, { name = "typer" }, { name = "uvicorn" }, ] @@ -3522,7 +3509,6 @@ dev = [ { name = "psutil" }, { name = "psycopg", extras = ["binary"] }, { name = "pydantic" }, - { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, @@ -3540,6 +3526,7 @@ dev = [ { name = "sqlmodel" }, { name = "starlette-admin" }, { name = "toml" }, + { name = "ty" }, { name = "typer" }, { name = "uvicorn" }, ] @@ -4488,6 +4475,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/e3/d81b065a2d866a33a541ac63a2a4cc5737e03ce2379ac3191c98bb8867e3/trove_classifiers-2026.5.7.17-py3-none-any.whl", hash = "sha256:5ec0800de5e2ddbd7c663cb4c0c15328f132dc168813897c18866c5c7b93db33", size = 14201, upload-time = "2026-05-07T17:48:00.488Z" }, ] +[[package]] +name = "ty" +version = "0.0.39" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/8d/7b5c74dc287fbcb37bae9853cec13bf44717c1735298500e4aeba31579a9/ty-0.0.39.tar.gz", hash = "sha256:f750277e76a01ecd86185960eca73823c26a53c51103568d56d4d904575159fd", size = 5702365, upload-time = "2026-05-22T21:09:56.403Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/17/9b89802c26d12d0f7a27bc25d4066d941d42891e8898f9f26499f0067e32/ty-0.0.39-py3-none-linux_armv6l.whl", hash = "sha256:c1bb7ac70f1f7d70cc6655fd96558039e4562b10f489fa49c7ebfd5fcee73ad1", size = 11360431, upload-time = "2026-05-22T21:09:18.689Z" }, + { url = "https://files.pythonhosted.org/packages/9c/c6/663ded50e823dbf9fb9d002eca46b7cb1fb2c72b744b84f22ce732a0ee0b/ty-0.0.39-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3435b64c1e59c14c9aa39c20cc018823937cd38d55db853e74d95b8f420569b0", size = 11096281, upload-time = "2026-05-22T21:09:15.383Z" }, + { url = "https://files.pythonhosted.org/packages/8b/ae/5d38ba9a6456ff4c78d212cf464fd8b9a25d8118465197b0b2dc891c0b19/ty-0.0.39-py3-none-macosx_11_0_arm64.whl", hash = "sha256:5f136377ce46c73677701a9e1ad730bf72f699bcec046e422eb79d0886cac3ab", size = 10529674, upload-time = "2026-05-22T21:09:46.471Z" }, + { url = "https://files.pythonhosted.org/packages/be/6f/43638cb8106445d3c8817256a0731cde9dd7b6a53ae2e881294bc1930ca3/ty-0.0.39-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:36b65fb0cc17f03e851d40e210d420be94ab8bc52d041328ad1e45f616036a61", size = 11055561, upload-time = "2026-05-22T21:09:36.981Z" }, + { url = "https://files.pythonhosted.org/packages/91/17/95e62cf4458527ce78dc386eba18f8b10c3fb64cd8c9e7e59b262ff6029d/ty-0.0.39-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4967967bfadf3860ff84c3fccdbaec8edf8aa20d0d727521084733d853de6657", size = 11127185, upload-time = "2026-05-22T21:09:31.395Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c0/93666c213db5c71ab1b1f1a0db5f66bf8c7c0e0b0bf59859f5da8f0b3c36/ty-0.0.39-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9e10ecb1297099ddf9a1f054f8bd921d1863ce85fb819a3c96ed27865a1ba6ed", size = 11608459, upload-time = "2026-05-22T21:09:12.862Z" }, + { url = "https://files.pythonhosted.org/packages/79/85/3b26585afc8b50230d6464bb0642feef4fab3f847e38b1f0ffa971a81446/ty-0.0.39-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9b19cca70e465d71b0510656343883d62372bbe74b7845cae7c0e701d6d5264b", size = 12177101, upload-time = "2026-05-22T21:09:40.519Z" }, + { url = "https://files.pythonhosted.org/packages/49/4a/1039e4f6afc576dc1c3a4d22a6478904a1ad3766597cd0b93c077ab9dfce/ty-0.0.39-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:56c6704b01b9b3d80ff26b2918423b742516d1e469bef830e9254dcedc9185bf", size = 11827815, upload-time = "2026-05-22T21:09:49.89Z" }, + { url = "https://files.pythonhosted.org/packages/e2/c5/4688652870e350a76a8157f7ffb59ad54f37d5d10725aa7076f66ac94ec8/ty-0.0.39-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40b7840ff46764b6a6757f4ade1cd0530fc3e8a0b435ca93e7602360e4cb90b6", size = 11694429, upload-time = "2026-05-22T21:09:21.568Z" }, + { url = "https://files.pythonhosted.org/packages/fc/72/8a1c4e823bb5bdc935a1c8140e100304e36a68a4139592f170aa9736fdb7/ty-0.0.39-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:1c62a3a87ce26b50819f0dbf03bd95f23f19eeb87bbc7aa732ec64277c77f1aa", size = 11869846, upload-time = "2026-05-22T21:09:28.053Z" }, + { url = "https://files.pythonhosted.org/packages/17/9f/cf982457b861ae22d657c5dcdbc631199f7f90264279db1d17230dfbc3ff/ty-0.0.39-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f8c34bc81a9c3516e49904e9d8330aac385377cca98390193ea02b903a40fcf0", size = 11029763, upload-time = "2026-05-22T21:09:06.791Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/95b64f6d43ae6e8f0b7e13dacf9c196d35819af22b1924171fba31383156/ty-0.0.39-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:66f5ab11586a64e79cb692ad685ee5469325c31b5f30bd3554f52f36dbe28cc4", size = 11146761, upload-time = "2026-05-22T21:09:10.178Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/0a89cfb06f7632a05bf56c78e0affb4a40f81759e275376cea75c9c5abe9/ty-0.0.39-py3-none-musllinux_1_2_i686.whl", hash = "sha256:e8d89732bcbbcb091f439e556dfc4932f198b118b47d5b85212c60662099670e", size = 11281843, upload-time = "2026-05-22T21:09:34.234Z" }, + { url = "https://files.pythonhosted.org/packages/0e/53/64c4a27067a46643fea2b3fcf21a8a2f838d91a65ffdd14f2e82945b9538/ty-0.0.39-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:eceb6c91dcd05a231119f82abdd9aa337513de23ca6ac990bc44f88791dc1799", size = 11792477, upload-time = "2026-05-22T21:09:24.923Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e8/02f4dd4a12bcdbda0006f9c7ff3b99a4be06bd0d257d3bd4a5b66de074e6/ty-0.0.39-py3-none-win32.whl", hash = "sha256:891c3262314dbc80bf3e872634d23dd216306945daa9a9fcc206ce5ed21ac4c9", size = 10615377, upload-time = "2026-05-22T21:09:43.167Z" }, + { url = "https://files.pythonhosted.org/packages/b5/5a/aaeb22faa8d4dae90a287d4c3636c671edcff3b99be5f4fc8b79ad71eef6/ty-0.0.39-py3-none-win_amd64.whl", hash = "sha256:ba7f2d54452535419e90f6f03ff39282999e87b43c21c00559f6d7ad711a36d5", size = 11710711, upload-time = "2026-05-22T21:09:53.179Z" }, + { url = "https://files.pythonhosted.org/packages/a3/17/ae7339651bfcaa5f54698c8c70eaf5031baa400ecb67baec31d03a56cbd4/ty-0.0.39-py3-none-win_arm64.whl", hash = "sha256:eb4cf0fefbbfedf9a352597bb2431ebdcb7eb3a595c0f825f228e897a0ec285d", size = 11081409, upload-time = "2026-05-22T21:09:03.741Z" }, +] + [[package]] name = "typer" version = "0.25.1"