diff --git a/.github/workflows/check_outdated_dependencies.yml b/.github/workflows/check_outdated_dependencies.yml index 1a206f2697b..4959638a23e 100644 --- a/.github/workflows/check_outdated_dependencies.yml +++ b/.github/workflows/check_outdated_dependencies.yml @@ -29,14 +29,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 a06454f5d16..9af827ba829 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: 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/docs/app/reflex_docs/pages/docs/cloud_cliref.py b/docs/app/reflex_docs/pages/docs/cloud_cliref.py index b8051fba339..ee08864dcc8 100644 --- a/docs/app/reflex_docs/pages/docs/cloud_cliref.py +++ b/docs/app/reflex_docs/pages/docs/cloud_cliref.py @@ -260,7 +260,7 @@ def process_command(command: click.Command, name: str) -> str: if find_spec("typer") is not None and find_spec("typer.main") is not None: - import typer # pyright: ignore[reportMissingImports] + import typer # ty: ignore[unresolved-import] if isinstance(cli, typer.Typer): cli = typer.main.get_command(cli) diff --git a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py index c6fe09c239a..a1ddd91b8ee 100644 --- a/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py +++ b/docs/app/reflex_docs/templates/docpage/sidebar/sidebar.py @@ -609,17 +609,17 @@ def sidebar_comp( html_lib_index, url, ), - rx.link( # pyright: ignore [reportCallIssue] - rx.box( # pyright: ignore [reportCallIssue] - rx.box( # pyright: ignore [reportCallIssue] - rx.icon("atom", size=16), # pyright: ignore [reportCallIssue] + rx.link( # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] + rx.box( # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] + rx.box( # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] + rx.icon("atom", size=16), # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] rx.el.h5( "Custom Components", class_name="font-smbold text-[0.875rem] text-slate-12 leading-5 tracking-[-0.01313rem] transition-color", ), class_name="flex flex-row items-center gap-3 text-slate-12", ), - rx.text( # pyright: ignore [reportCallIssue] + rx.text( # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] "See what components people have made with Reflex!", class_name="font-small text-slate-9", ), @@ -693,7 +693,7 @@ def sidebar_comp( class_name="m-0 p-0 flex flex-col items-start gap-8 w-full list-none list-style-none", ) - return rx.box( # pyright: ignore [reportCallIssue] + return rx.box( # ty:ignore[missing-argument, unknown-argument, call-non-callable, too-many-positional-arguments, no-matching-overload] categories, content, style={ diff --git a/docs/app/reflex_docs/utils/http.py b/docs/app/reflex_docs/utils/http.py index 5ee033d5a82..f8ee50e985f 100644 --- a/docs/app/reflex_docs/utils/http.py +++ b/docs/app/reflex_docs/utils/http.py @@ -26,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 diff --git a/docs/getting_started/chat_tutorial_utils.py b/docs/getting_started/chat_tutorial_utils.py index 4bf4a7d1859..ca1a2565c57 100644 --- a/docs/getting_started/chat_tutorial_utils.py +++ b/docs/getting_started/chat_tutorial_utils.py @@ -4,7 +4,7 @@ import os -import openai # pyright: ignore[reportMissingImports] +import openai # ty: ignore[unresolved-import] import reflex as rx diff --git a/packages/reflex-base/src/reflex_base/components/component.py b/packages/reflex-base/src/reflex_base/components/component.py index 2605e2f2315..e1ba91c3777 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 @@ -111,7 +112,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: @@ -129,7 +130,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, @@ -401,7 +402,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: @@ -428,7 +429,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: @@ -614,15 +615,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( @@ -1045,7 +1046,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. @@ -1289,9 +1290,9 @@ 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 (style := styles.get(type(self))) is not None: # ty:ignore[invalid-argument-type] 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: # ty:ignore[invalid-argument-type] component_style = Style(style) return component_style @@ -2213,13 +2214,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(self.component_fn.__name__) # ty:ignore[unresolved-attribute] for key, value in props.items(): # Skip kwargs that are not props. @@ -2293,7 +2294,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, @@ -2545,7 +2546,7 @@ def empty_component() -> Component: return Bare.create("") -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: @@ -2560,31 +2561,32 @@ def render_dict_to_var(tag: dict | Component | str) -> Var: return Var.create(tag) if "contents" in tag: - return Var(tag["contents"]) + return Var(tag["contents"]) # ty:ignore[invalid-argument-type] if "iterable" in tag: function_return = LiteralArrayVar.create([ - render_dict_to_var(child.render()) for child in tag["children"] + render_dict_to_var(child.render()) + for child in tag["children"] # ty:ignore[invalid-argument-type, not-iterable] ]) func = ArgsFunctionOperation.create( - (tag["arg_var_name"], tag["index_var_name"]), + (tag["arg_var_name"], tag["index_var_name"]), # ty:ignore[invalid-argument-type] function_return, ) return FunctionStringVar.create("Array.prototype.map.call").call( - tag["iterable"] - if not isinstance(tag["iterable"], ObjectVar) - else tag["iterable"].items(), + tag["iterable"] # ty:ignore[invalid-argument-type] + if not isinstance(tag["iterable"], ObjectVar) # ty:ignore[invalid-argument-type] + else tag["iterable"].items(), # ty:ignore[invalid-argument-type] func, ) if "match_cases" in tag: - element = Var(tag["cond"]) + element = Var(tag["cond"]) # ty:ignore[invalid-argument-type] - conditionals = render_dict_to_var(tag["default"]) + conditionals = render_dict_to_var(tag["default"]) # ty:ignore[invalid-argument-type] - for case in tag["match_cases"][::-1]: + for case in tag["match_cases"][::-1]: # ty:ignore[invalid-argument-type, not-subscriptable] conditions, return_value = case condition = Var.create(False) for pattern in conditions: @@ -2602,16 +2604,16 @@ def render_dict_to_var(tag: dict | Component | str) -> Var: if "cond_state" in tag: 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(tag["cond_state"]), # ty:ignore[invalid-argument-type] + render_dict_to_var(tag["true_value"]), # ty:ignore[invalid-argument-type] + render_dict_to_var(tag["false_value"]) # ty:ignore[invalid-argument-type] + if tag["false_value"] is not None # ty:ignore[invalid-argument-type] else LiteralNoneVar.create(), ) - props = Var("({" + ",".join(tag["props"]) + "})") + props = Var("({" + ",".join(tag["props"]) + "})") # ty:ignore[invalid-argument-type, no-matching-overload] - raw_tag_name = tag.get("name") + raw_tag_name = tag.get("name") # ty:ignore[invalid-argument-type] tag_name = Var(raw_tag_name or "Fragment") return FunctionStringVar.create( @@ -2619,7 +2621,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 tag["children"]], # ty:ignore[invalid-argument-type, not-iterable] ) 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 f2d4ce44cb9..d6fb8caae57 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 @@ -709,7 +709,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 740f33ebc82..5713db86d98 100644 --- a/packages/reflex-base/src/reflex_base/event/__init__.py +++ b/packages/reflex-base/src/reflex_base/event/__init__.py @@ -116,7 +116,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: @@ -404,7 +404,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: @@ -413,7 +413,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: @@ -510,7 +510,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="") @@ -722,7 +722,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)) @@ -987,7 +987,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]]]: ... @@ -1002,7 +1002,7 @@ def passthrough_event_spec( 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: @@ -1015,22 +1015,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 @@ -1226,7 +1226,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( @@ -1945,7 +1945,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)] @@ -1955,11 +1955,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 @@ -2165,7 +2165,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) @@ -2225,7 +2225,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. @@ -2261,7 +2261,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( @@ -2312,7 +2312,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. @@ -2345,7 +2345,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) @@ -2382,7 +2382,7 @@ def create( LiteralVar.create([LiteralVar.create(event)]), arg_def_expr, _EMPTY_EVENT_ACTIONS, - ) + ) # ty:ignore[no-matching-overload] ) for event in value.events ] @@ -2393,7 +2393,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: @@ -2446,7 +2446,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__( @@ -2482,7 +2482,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: @@ -2491,7 +2491,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__( @@ -2499,7 +2499,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]]]": ... # ty:ignore[invalid-type-form] def __get__(self, instance: Any, owner: Any) -> Callable: """Get the function with the instance bound to it. @@ -2759,7 +2759,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(".", "_") @@ -2785,7 +2785,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) @@ -2839,7 +2839,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 @@ -2855,9 +2855,9 @@ def BaseState(self) -> "type[BaseState]": # noqa: N802 event = EventNamespace -event.event = event # pyright: ignore[reportAttributeAccessIssue] +event.event = event # ty:ignore[unresolved-attribute] _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__ # ty:ignore[unresolved-attribute] +event.__spec__ = _this.__spec__ # ty:ignore[unresolved-attribute] +event.__package__ = _this.__package__ # ty:ignore[unresolved-attribute] +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..88ee1dc8827 100644 --- a/packages/reflex-base/src/reflex_base/event/context.py +++ b/packages/reflex-base/src/reflex_base/event/context.py @@ -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__", cls.__name__).replace(".", "___") # ty:ignore[unresolved-attribute] 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..ccbe0584576 100644 --- a/packages/reflex-base/src/reflex_base/plugins/compiler.py +++ b/packages/reflex-base/src/reflex_base/plugins/compiler.py @@ -490,7 +490,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 +577,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 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..0094e553cb8 100644 --- a/packages/reflex-base/src/reflex_base/style.py +++ b/packages/reflex-base/src/reflex_base/style.py @@ -154,7 +154,7 @@ def convert_list( for responsive_item in responsive_list: if isinstance(responsive_item, dict): # Recursively format nested style dictionaries. - item, item_var_data = convert(responsive_item) + item, item_var_data = convert(responsive_item) # ty:ignore[invalid-argument-type] else: item, item_var_data = convert_item(responsive_item) converted_value.append(item) @@ -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/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..f7f00371fca 100644 --- a/packages/reflex-base/src/reflex_base/utils/decorator.py +++ b/packages/reflex-base/src/reflex_base/utils/decorator.py @@ -24,7 +24,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 @@ -66,7 +66,7 @@ def debug(f: Callable[P, T]) -> Callable[P, T]: 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 {f.__name__} with args: {args} and kwargs: {kwargs}, result: {result}" # ty:ignore[unresolved-attribute] ) return result @@ -108,7 +108,7 @@ 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] def _inner(*args: P.args, **kwargs: P.kwargs) -> Picklable: cache_file = cache_file_path() @@ -123,7 +123,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 {func.__name__} with payload: {new_payload}" # ty:ignore[unresolved-attribute] ) 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..3736154c077 100644 --- a/packages/reflex-base/src/reflex_base/utils/format.py +++ b/packages/reflex-base/src/reflex_base/utils/format.py @@ -404,7 +404,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 +577,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..5d36f433ced 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,7 @@ 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", origin.__name__) # ty:ignore[unresolved-attribute] # Get type arguments args = get_args(typ) @@ -837,7 +838,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 +967,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 +1019,7 @@ def _generate_staticmethod_call_functiondef( else [] ), ) - return ast.FunctionDef( # pyright: ignore [reportCallIssue] + return ast.FunctionDef( name="__call__", args=call_args, body=[ @@ -1067,7 +1070,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 +1161,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..fa5348186ac 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 @@ -304,7 +304,7 @@ def has_args(cls: type) -> bool: # Check if the class inherits from a generic class (using __orig_bases__) if hasattr(cls, "__orig_bases__"): - for base in cls.__orig_bases__: + for base in cls.__orig_bases__: # ty:ignore[not-iterable] if get_args(base): return True @@ -461,13 +461,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 +485,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 +494,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 +510,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 +540,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 @@ -933,9 +933,9 @@ def validate_literal(key: str, value: Any, expected_type: type, comp_name: str): 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_type.__args__ # ty:ignore[unresolved-attribute] ): - allowed_values = expected_type.__args__ + allowed_values = expected_type.__args__ # ty:ignore[unresolved-attribute] 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 diff --git a/packages/reflex-base/src/reflex_base/vars/base.py b/packages/reflex-base/src/reflex_base/vars/base.py index 4034b69aa3c..a22aed7096e 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 @@ -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: @@ -1385,10 +1386,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="", # ty:ignore[unknown-argument] + _var_data=_var_data, # ty:ignore[unknown-argument] + _var_type=_var_type or cls._default_var_type, # ty:ignore[unknown-argument, unresolved-attribute] + _original=value, # ty:ignore[unknown-argument] ) @@ -1649,7 +1650,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 +1662,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 +1712,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 +1744,9 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]: } return CustomVarOperation.create( - name=func.__name__, + name=func.__name__, # ty:ignore[unresolved-attribute] 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 +1769,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 +1913,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. @@ -2073,7 +2074,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="") @@ -2109,9 +2110,9 @@ def __init__( ) if hint is Any: - raise UntypedComputedVarError(var_name=fget.__name__) + raise UntypedComputedVarError(var_name=fget.__name__) # ty:ignore[unresolved-attribute] 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) # ty:ignore[unresolved-attribute] kwargs.setdefault("_var_type", hint) Var.__init__( @@ -2120,7 +2121,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, # ty:ignore[unresolved-attribute] ), ) @@ -2129,12 +2130,12 @@ def __init__( raise TypeError(msg) if backend is None: - backend = fget.__name__.startswith("_") + backend = fget.__name__.startswith("_") # ty:ignore[unresolved-attribute] 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__) # ty:ignore[unresolved-attribute] if isinstance(interval, int): interval = datetime.timedelta(seconds=interval) @@ -2359,18 +2360,18 @@ 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() + while self._name in state_where_defined.inherited_vars: # ty:ignore[unresolved-attribute] + state_where_defined = state_where_defined.get_parent_state() # ty:ignore[unresolved-attribute] field_name = ( - format_state_name(state_where_defined.get_full_name()) + format_state_name(state_where_defined.get_full_name()) # ty:ignore[unresolved-attribute] + "." + self._js_expr ) return dispatch( field_name, - var_data=VarData.from_state(state_where_defined, self._name), + var_data=VarData.from_state(state_where_defined, self._name), # ty:ignore[invalid-argument-type] result_var_type=self._var_type, existing_var=self, ) @@ -2507,7 +2508,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: @@ -2769,7 +2770,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(fget.__name__, signature=str(sign)) # ty:ignore[unresolved-attribute] if inspect.iscoroutinefunction(fget): computed_var_cls = AsyncComputedVar @@ -3140,13 +3141,13 @@ def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]: origin = get_origin(return_type) 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}." # ty:ignore[unresolved-attribute] 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." # ty:ignore[unresolved-attribute] raise TypeError(msg) generic_type = get_origin(generic_args[0]) or generic_args[0] @@ -3197,7 +3198,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}." # ty:ignore[unresolved-attribute] raise TypeError(msg) fn_return_generic_args = get_args(fn_return) @@ -3209,7 +3210,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}." # ty:ignore[unresolved-attribute] raise TypeError(msg) arg_generic_args = get_args(fn_first_arg_type) @@ -3275,8 +3276,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. @@ -3300,7 +3300,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: @@ -3310,7 +3310,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: @@ -3433,7 +3433,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: @@ -3448,7 +3448,7 @@ def field( *, is_var: Literal[False], default_factory: Callable[[], FIELD_TYPE] | None = None, -) -> FIELD_TYPE: ... +) -> Any: ... @overload @@ -3457,7 +3457,7 @@ def field( *, default_factory: Callable[[], FIELD_TYPE] | None = None, is_var: Literal[True] = True, -) -> Field[FIELD_TYPE]: ... +) -> Any: ... def field( @@ -3630,6 +3630,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 30cda3c3679..1e9d6edcb80 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..891ac6c124c 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 @@ -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..c2a756f9dd8 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 @@ -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 aef4a4ebf14..9f887817d1f 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-dataeditor/src/reflex_components_dataeditor/dataeditor.py b/packages/reflex-components-dataeditor/src/reflex_components_dataeditor/dataeditor.py index b5399be80cc..b8f91d49f2a 100644 --- a/packages/reflex-components-dataeditor/src/reflex_components_dataeditor/dataeditor.py +++ b/packages/reflex-components-dataeditor/src/reflex_components_dataeditor/dataeditor.py @@ -364,7 +364,7 @@ class DataEditor(NoSSRComponent): ) on_finished_editing: EventHandler[ - passthrough_event_spec(GridCell | None, tuple[int, int]) + passthrough_event_spec(GridCell | None, tuple[int, int]) # ty:ignore[no-matching-overload] ] = field(doc="Fired when editing is finished.") on_row_appended: EventHandler[no_args_event_spec] = field( 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/context_menu.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/context_menu.py index 2e69eba8c9b..9b1ec268c98 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/context_menu.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/context_menu.py @@ -377,7 +377,7 @@ class ContextMenuRadioGroup(ContextMenuBaseComponent): value: Var[str | int] # Event handler called when the value changes. - on_value_change: EventHandler[passthrough_event_spec(str | int, dict)] + on_value_change: EventHandler[passthrough_event_spec(str | int, dict)] # ty:ignore[no-matching-overload] # Whether the component should ignore user interaction. Defaults to False. disabled: Var[bool] 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-internal/src/reflex_components_internal/components/base/menu.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/menu.py index 84429654c75..dda6d6823fe 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/menu.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/menu.py @@ -461,7 +461,7 @@ class MenuRadioGroup(MenuBaseComponent): value: Var[str | int] # Function called when the selected value changes. - on_value_change: EventHandler[passthrough_event_spec(str | int, dict)] + on_value_change: EventHandler[passthrough_event_spec(str | int, dict)] # ty:ignore[no-matching-overload] # Whether the component should ignore user interaction. Defaults to False. disabled: Var[bool] diff --git a/packages/reflex-components-internal/src/reflex_components_internal/components/base/tabs.py b/packages/reflex-components-internal/src/reflex_components_internal/components/base/tabs.py index 4fe83c92479..0a3ef5ff0a4 100644 --- a/packages/reflex-components-internal/src/reflex_components_internal/components/base/tabs.py +++ b/packages/reflex-components-internal/src/reflex_components_internal/components/base/tabs.py @@ -62,7 +62,7 @@ class TabsRoot(TabsBaseComponent): value: Var[str | int] # Callback invoked when new value is being set. - on_value_change: EventHandler[passthrough_event_spec(str | dict)] + on_value_change: EventHandler[passthrough_event_spec(str | dict)] # ty:ignore[no-matching-overload] # The component orientation (layout flow direction). Defaults to "horizontal". orientation: Var[LiteralOrientation] 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 30a0cd65d75..7be4e5e1091 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 106dcedf475..b860ac7edaf 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/v2/cli.py @@ -379,7 +379,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: @@ -406,7 +406,7 @@ def deploy( False, True, True, - ) # pyright: ignore[reportCallIssue] + ) # ty:ignore[missing-argument] else: export_fn( str(temporary_dir_path), @@ -415,7 +415,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}") @@ -427,7 +427,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), @@ -436,7 +436,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 8042bf8f6c5..d1047329c0c 100644 --- a/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py +++ b/packages/reflex-hosting-cli/src/reflex_cli/v2/deployments.py @@ -92,7 +92,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 @@ -102,7 +102,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 75a193845f0..64695d10cc4 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": "82d8699470071df80886a4a6ba8dccfe" + "reflex/experimental/memo.pyi": "183af3dc3fea982b14300951d503031c" } diff --git a/pyproject.toml b/pyproject.toml index 778c9c49bf4..29ed1369255 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 65ae0a8235b..d1331fd0154 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -688,7 +688,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): @@ -843,7 +843,7 @@ 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(component.__name__)) # ty:ignore[unresolved-attribute] else: route = format.format_route(route) @@ -1228,7 +1228,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, diff --git a/reflex/app_mixins/lifespan.py b/reflex/app_mixins/lifespan.py index 13642e7e458..8b16da490ce 100644 --- a/reflex/app_mixins/lifespan.py +++ b/reflex/app_mixins/lifespan.py @@ -34,7 +34,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 task.__name__ # ty:ignore[unresolved-attribute] @dataclasses.dataclass @@ -122,7 +122,7 @@ async def _run_lifespan_tasks(self, app: Starlette): task.cancel(msg="lifespan_cleanup") # Disassociate sid / token pairings so they can be reconnected properly. try: - event_namespace = self.event_namespace # pyright: ignore[reportAttributeAccessIssue] + event_namespace = self.event_namespace # ty:ignore[unresolved-attribute] except AttributeError: pass else: @@ -133,7 +133,7 @@ async def _run_lifespan_tasks(self, app: Starlette): 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] + state_manager = self.state_manager # ty:ignore[unresolved-attribute] except (AttributeError, ValueError): pass else: @@ -183,7 +183,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 {task.__name__} of type generator must be decorated with contextlib.asynccontextmanager." # ty:ignore[unresolved-attribute] 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 39ff4931a9e..d8c2d1d67b8 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -761,8 +761,8 @@ def readable_name_from_component( if module is not None: module_name = module.__name__ if module_name is not None: - return f"{module_name}.{component.__name__}" - return component.__name__ + return f"{module_name}.{component.__name__}" # ty:ignore[unresolved-attribute] + return component.__name__ # ty:ignore[unresolved-attribute] return None @@ -813,7 +813,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) @@ -907,7 +907,7 @@ def compile_unevaluated_page( # Add meta information to the component. utils.add_meta( component, - **meta_args, + **meta_args, # ty:ignore[invalid-argument-type] ) 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 c2bdf618650..32d5df04c88 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") 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 3c88aca6cff..a071ea33b60 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, 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, ...] @@ -464,7 +465,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. @@ -540,7 +541,7 @@ def _lift_rest_props(component: Component) -> Component: def _analyze_params( - fn: Callable[..., Any], + fn: FunctionType, *, for_component: bool, ) -> tuple[MemoParam, ...]: @@ -558,28 +559,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) @@ -591,14 +593,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) @@ -606,9 +608,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) @@ -635,7 +635,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. @@ -679,13 +679,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. @@ -1096,7 +1097,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/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..d5f327c8969 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 cast(TOKEN_TYPE, state) # ty:ignore[redundant-cast] 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..c2bb149088d 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): @@ -770,7 +767,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(): # ty:ignore[unresolved-attribute] 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 43099e74332..56cc8057c15 100644 --- a/reflex/reflex.py +++ b/reflex/reflex.py @@ -928,7 +928,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..6dc5126fbe4 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: builtins.dict[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 9a3ff023049..7e13a4decc0 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -67,7 +67,7 @@ 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 @@ -120,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( @@ -152,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 = app_source.func.__name__ # ty:ignore[unresolved-attribute] 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 = app_source.__name__ # ty:ignore[unresolved-attribute] app_name = app_name.lower() while "__" in app_name: @@ -249,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([ @@ -406,9 +406,7 @@ def _wait_frontend(self): def consume_frontend_output(): while True: try: - line = ( - self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess] - ) + line = self.frontend_process.stdout.readline() # ty:ignore[unresolved-attribute] # catch I/O operation on closed file. except ValueError as e: console.error(str(e)) @@ -635,29 +633,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: @@ -674,7 +672,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 @@ -874,8 +872,8 @@ def finish_request(self, request: socket.socket, client_address: tuple[str, int] request, client_address, self, - directory=str(self.root), # pyright: ignore [reportCallIssue] - error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue] + directory=str(self.root), # ty:ignore[unknown-argument] + error_page_map=self.error_page_map, # ty:ignore[unknown-argument] ) 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 0889e9359e1..da7e0875794 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -200,7 +200,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/prerequisites.py b/reflex/utils/prerequisites.py index af0e2c14ef6..ac7c5fb33b5 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -320,7 +320,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 @@ -359,7 +359,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..26618c49fc7 100644 --- a/reflex/utils/processes.py +++ b/reflex/utils/processes.py @@ -255,7 +255,7 @@ 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 @@ -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..3c576d3e40a 100644 --- a/reflex/utils/tasks.py +++ b/reflex/utils/tasks.py @@ -47,10 +47,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"{coro_function.__name__}: task exceeded exception limit {exception_limit} within {exception_limit_window}s: {e}" # ty:ignore[unresolved-attribute] ) raise - console.error(f"{coro_function.__name__}: task error suppressed: {e}") + console.error(f"{coro_function.__name__}: task error suppressed: {e}") # ty:ignore[unresolved-attribute] await asyncio.sleep(exception_delay) continue raise @@ -105,7 +105,7 @@ 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()}" + task_name = f"reflex_ensure_task|{type(owner).__name__}.{task_attribute}={coro_function.__name__}|{time.time()}" # ty:ignore[unresolved-attribute] 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 dcdecd5e0a9..fb8088d6165 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -293,7 +293,7 @@ def _prepare_event(event: str, **kwargs) -> _Event | None: if key in properties or key not in kwargs: continue - properties[key] = kwargs[key] + properties[key] = kwargs[key] # ty:ignore[invalid-key] stamp = datetime.now(UTC).isoformat() 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..6ab1720d9f7 100644 --- a/tests/integration/test_event_actions.py +++ b/tests/integration/test_event_actions.py @@ -76,12 +76,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"), # ty:ignore[invalid-argument-type, missing-argument] 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, # ty:ignore[invalid-argument-type, missing-argument] id="btn-click-stop-propagation", ), rx.button( @@ -97,15 +97,15 @@ 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"), # ty:ignore[invalid-argument-type, missing-argument] id="link", ), rx.link( "Link Stop Propagation", href="?link-stop-propagation", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] - "link_stop_propagation" - ).stop_propagation, + on_click=EventActionState.on_click( + "link_stop_propagation" # ty:ignore[invalid-argument-type] + ).stop_propagation, # ty:ignore[missing-argument] id="link-stop-propagation", ), rx.link( @@ -117,44 +117,42 @@ def index(): rx.link( "Link Prevent Default", href="/invalid", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] - "link_prevent_default" - ).prevent_default, + on_click=EventActionState.on_click( + "link_prevent_default" # ty:ignore[invalid-argument-type] + ).prevent_default, # ty:ignore[missing-argument] id="link-prevent-default", ), rx.link( "Link Both", href="/invalid", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] - "link_both" - ).stop_propagation.prevent_default, + on_click=EventActionState.on_click( + "link_both" # ty:ignore[invalid-argument-type] + ).stop_propagation.prevent_default, # ty:ignore[missing-argument] id="link-stop-propagation-prevent-default", ), EventFiringComponent.create( id="custom-stop-propagation", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] - "custom-stop-propagation" - ).stop_propagation, + on_click=EventActionState.on_click( + "custom-stop-propagation" # ty:ignore[invalid-argument-type] + ).stop_propagation, # ty:ignore[missing-argument] ), EventFiringComponent.create( id="custom-prevent-default", - on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] - "custom-prevent-default" - ).prevent_default, + on_click=EventActionState.on_click( + "custom-prevent-default" # ty:ignore[invalid-argument-type] + ).prevent_default, # ty:ignore[missing-argument] ), rx.button( "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 # ty:ignore[unresolved-attribute] ), ), rx.button( "Debounce", id="btn-debounce", - on_click=EventActionState.on_click_debounce.debounce( # pyright: ignore [reportFunctionMemberAccess] + on_click=EventActionState.on_click_debounce.debounce( # ty:ignore[unresolved-attribute] 200 ).stop_propagation, ), @@ -165,7 +163,7 @@ def index(): ), id="event_order", ), - on_click=EventActionState.on_click("outer"), # pyright: ignore [reportCallIssue] + on_click=EventActionState.on_click("outer"), # ty:ignore[invalid-argument-type, missing-argument] ), rx.form( rx.dialog.root( rx.dialog.trigger( @@ -176,12 +174,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 +359,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..bdf956c7cf5 100644 --- a/tests/integration/test_exception_handlers.py +++ b/tests/integration/test_exception_handlers.py @@ -53,7 +53,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), # ty:ignore[invalid-argument-type, missing-argument] 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_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 8434938a894..947d2be1b1d 100644 --- a/tests/integration/tests_playwright/test_frontend_path.py +++ b/tests/integration/tests_playwright/test_frontend_path.py @@ -41,7 +41,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 @@ -180,7 +180,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 fe859984346..40f954dfd5f 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 a715b930436..20260429ba8 100644 --- a/tests/units/compiler/test_memoize_plugin.py +++ b/tests/units/compiler/test_memoize_plugin.py @@ -272,7 +272,7 @@ def special_child() -> Component: rx.text("yes"), rx.text("no"), ), - ) + ) # ty:ignore[redundant-cast] return cast( Component, rx.match( @@ -370,7 +370,7 @@ def test_common_memoization_snapshot_helper_classifies_snapshot_cases() -> None: rx.text("yes"), rx.text("no"), ), - ) + ) # ty:ignore[redundant-cast] match_fragment = cast( Component, rx.match( 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 f3ea3c03228..e38695ecf1a 100644 --- a/tests/units/components/forms/test_form.py +++ b/tests/units/components/forms/test_form.py @@ -10,7 +10,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 9ca3495a2a2..50b7b7e597f 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 @@ -1368,17 +1368,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)), # ty:ignore[invalid-argument-type, missing-argument] [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)), # ty:ignore[invalid-argument-type, missing-argument] [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)), # ty:ignore[invalid-argument-type, missing-argument] [ARG_VAR, TEST_VAR], id="direct-event-handler-lambda", ), @@ -1684,7 +1684,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 +1869,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 +1881,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 +1911,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 +1924,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 +2003,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 +2121,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..3c14a600084 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] > expires_at # ty:ignore[unsupported-operator] 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] > expires_at # ty:ignore[unsupported-operator] 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] > expires_at # ty:ignore[unsupported-operator] 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] > expires_at # ty:ignore[unsupported-operator] 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_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 a772b3a3eae..64314920db2 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -192,16 +192,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 @@ -535,7 +535,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): @@ -771,7 +771,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.""" @@ -809,7 +809,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.""" @@ -817,7 +817,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() @@ -1093,7 +1093,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 @@ -1203,7 +1203,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) @@ -1239,7 +1239,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 @@ -1248,7 +1248,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): @@ -1286,7 +1286,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 @@ -1339,7 +1339,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 @@ -1755,7 +1755,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( @@ -1807,7 +1807,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) @@ -1931,14 +1931,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() @@ -2049,7 +2049,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 @@ -2310,19 +2310,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(): @@ -2383,7 +2383,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 c294e4894cf..d3d810f63ae 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): @@ -342,7 +342,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) @@ -512,14 +512,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) @@ -533,14 +533,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] @@ -569,7 +569,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. @@ -579,7 +579,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(): @@ -590,4 +590,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 8e7796b3ebe..06563c97cf6 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 c332a57b892..10c3ab5c7cb 100644 --- a/tests/units/test_event.py +++ b/tests/units/test_event.py @@ -452,7 +452,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 @@ -614,7 +614,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 @@ -689,12 +689,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 c9cb76c3c0b..51a01535075 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -93,7 +93,7 @@ def test_initialise_vite_config(config, expected_output): 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 1ecf1ce1081..042c04bff74 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -123,7 +123,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 @@ -288,7 +288,7 @@ def test_state() -> TestState: Returns: A test state. """ - return TestState() # pyright: ignore [reportCallIssue] + return TestState() # ty:ignore[missing-argument] @pytest.fixture @@ -468,13 +468,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})' @@ -594,11 +594,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() @@ -1109,22 +1109,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): @@ -1548,7 +1548,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) @@ -2036,11 +2036,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 @@ -2048,7 +2048,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 @@ -2091,17 +2091,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()), @@ -2153,7 +2153,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) @@ -2204,7 +2204,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 @@ -2810,7 +2810,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() @@ -2830,7 +2830,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() @@ -2902,10 +2902,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() @@ -3062,7 +3062,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 @@ -3105,21 +3105,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 @@ -3181,31 +3181,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(): @@ -3368,7 +3366,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: @@ -3432,7 +3430,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: @@ -3875,9 +3873,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( @@ -4061,7 +4059,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"] ) @@ -4132,7 +4130,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" @@ -4152,8 +4150,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() @@ -4188,10 +4186,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() @@ -4219,7 +4217,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 @@ -4233,7 +4231,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) @@ -4241,7 +4239,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): @@ -4478,7 +4476,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 @@ -4893,7 +4891,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: @@ -4933,14 +4931,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_var.py b/tests/units/test_var.py index a96e4b2fb2e..c31fca099c1 100644 --- a/tests/units/test_var.py +++ b/tests/units/test_var.py @@ -1157,7 +1157,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"])' ) @@ -1167,7 +1167,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)' ) @@ -1364,7 +1364,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." @@ -1394,7 +1394,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 6d60c2f2109..b3e21057082 100644 --- a/tests/units/utils/test_format.py +++ b/tests/units/utils/test_format.py @@ -692,7 +692,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], @@ -726,7 +726,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_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 81f488a368e..6a962b3f86d 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" @@ -3441,7 +3428,6 @@ dev = [ { name = "psutil" }, { name = "psycopg", extra = ["binary"] }, { name = "pydantic" }, - { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, @@ -3459,6 +3445,7 @@ dev = [ { name = "sqlmodel" }, { name = "starlette-admin" }, { name = "toml" }, + { name = "ty" }, { name = "typer" }, { name = "uvicorn" }, ] @@ -3516,7 +3503,6 @@ dev = [ { name = "psutil" }, { name = "psycopg", extras = ["binary"] }, { name = "pydantic" }, - { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, @@ -3534,6 +3520,7 @@ dev = [ { name = "sqlmodel" }, { name = "starlette-admin" }, { name = "toml" }, + { name = "ty" }, { name = "typer" }, { name = "uvicorn" }, ] @@ -4482,6 +4469,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bb/4a/2e5583e544bc437d5e8e54b47db87430df9031b29b48d17f26d129fa60c0/trove_classifiers-2026.1.14.14-py3-none-any.whl", hash = "sha256:1f9553927f18d0513d8e5ff80ab8980b8202ce37ecae0e3274ed2ef11880e74d", size = 14197, upload-time = "2026-01-14T14:54:49.067Z" }, ] +[[package]] +name = "ty" +version = "0.0.34" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c4/69/e24eefe2c35c0fdbdec9b60e162727af669bb76d64d993d982eb67b24c38/ty-0.0.34.tar.gz", hash = "sha256:a6efe66b0f13c03a65e6c72ec9abfe2792e2fd063c74fa67e2c4930e29d661be", size = 5585933, upload-time = "2026-05-01T23:06:46.388Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/7b/8b85003d6639ef17a97dcbb31f4511cfe78f1c81a964470db100c8c883e7/ty-0.0.34-py3-none-linux_armv6l.whl", hash = "sha256:9ecc3d14f07a95a6ceb88e07f8e62358dbd37325d3d5bd56da7217ff1fef7fb8", size = 11067094, upload-time = "2026-05-01T23:06:21.133Z" }, + { url = "https://files.pythonhosted.org/packages/d7/25/b0098f65b020b015c40567c763fc66fffbec88b2ba6f584bca1e92f05ebb/ty-0.0.34-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:0dccffd8a9d02321cd2dee3249df205e26d62694e741f4eeca36b157fd8b419f", size = 10840909, upload-time = "2026-05-01T23:06:18.409Z" }, + { url = "https://files.pythonhosted.org/packages/e4/55/5e4adcf7d2a1006b844903b27cb81244a9b748d850433a46a6c21776c401/ty-0.0.34-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b0ea47a2998e167ab3b21d2f4b5309a9cf33c297809f6d7e3e753252223174d0", size = 10279378, upload-time = "2026-05-01T23:06:37.962Z" }, + { url = "https://files.pythonhosted.org/packages/4d/91/f537dca0db8fe2558e8ab04d8941d687b384fcc1df5eb9023b2db75ac26c/ty-0.0.34-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b37da00b41a118a459ae56d8947e70651073fb33ebfbceb820e4a10b22d5023", size = 10817423, upload-time = "2026-05-01T23:06:26.247Z" }, + { url = "https://files.pythonhosted.org/packages/2c/c4/55a3ad1da2815af1009bdc1b8c90dc11a364cd314e4b48c5128ba9d38859/ty-0.0.34-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:81cbbb93c2342fe3de43e625d3a9eb149633e9f485e816ebf6395d08685355d8", size = 10851826, upload-time = "2026-05-01T23:06:24.198Z" }, + { url = "https://files.pythonhosted.org/packages/ce/8c/9c7606af22d73fb43ea4369472d9c66ece11231be73b0efe8e3c61655559/ty-0.0.34-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4c5b4dea1594a021289e172582df9cde7089dce14b276fc650e7b212b1772e12", size = 11356318, upload-time = "2026-05-01T23:06:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/20/54/bb423f663721ab4138b216425c6b55eaefd3a068243b24d6d8fe988f4e13/ty-0.0.34-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:030fb00aa2d2a5b5ae9d9183d574e0c82dae80566700a7490c43669d8ece40cd", size = 11902968, upload-time = "2026-05-01T23:06:35.82Z" }, + { url = "https://files.pythonhosted.org/packages/b6/22/01122b21ab6b534a2f618c6bbe5f1f7f49fd56f4b2ec8887cd6d40d08fb3/ty-0.0.34-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ae9555e24e36c63a8218e037a5a63f15579eb6aa94f41017e57cd41d335cfb5", size = 11548860, upload-time = "2026-05-01T23:06:42.155Z" }, + { url = "https://files.pythonhosted.org/packages/d1/50/86008b1392ec64bed1957bbcc7aaa43b466b50dfc91bb131841c21d7c5c3/ty-0.0.34-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:99eb23df9ed129fc26d1ab00d6f0b8dfe5253b09c2ac6abdb11523fa70d67f10", size = 11457097, upload-time = "2026-05-01T23:06:53.477Z" }, + { url = "https://files.pythonhosted.org/packages/92/3e/4558b2296963ba99c58d8409c57d7db4f3061b656c3613cb21c02c1ef4c2/ty-0.0.34-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:85de45382016eceae69e104815eb2cfa200787df104002e262a86cbd43ed2c02", size = 10798192, upload-time = "2026-05-01T23:06:40.004Z" }, + { url = "https://files.pythonhosted.org/packages/76/bf/650d24402be2ef678528d60caac1d9477a40fc37e3792ecef07834fd7a4a/ty-0.0.34-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:14cb575fb8fa5131f5129d100cfe23c1575d23faf5dfc5158432749a3e38c9b5", size = 10890390, upload-time = "2026-05-01T23:06:33.076Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ef/ccd2ca13906079f7935fd7e067661b24233017f57d987d51d6a121d85bb5/ty-0.0.34-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c6fc0b69d8450e6910ba9db34572b959b81329a97ae273c391f70e9fb6c1aade", size = 11031564, upload-time = "2026-05-01T23:06:55.812Z" }, + { url = "https://files.pythonhosted.org/packages/ba/2d/d27b72005b6f43599e3bcabab0d7135ac0c230b7a307bb99f9eea02c1cda/ty-0.0.34-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:30dfcec2f0fde3993f4f912ed0e057dcbebc8615299f610a4c2ddb7b5a3e1e06", size = 11553430, upload-time = "2026-05-01T23:06:31.096Z" }, + { url = "https://files.pythonhosted.org/packages/a7/12/20812e1ad930b8d4af70eebf19ad23cff6e31efcfa613ef884531fcdbaa1/ty-0.0.34-py3-none-win32.whl", hash = "sha256:97b77ddf007271b812a313a8f0a14929bc5590958433e1fb83ef585676f53342", size = 10436048, upload-time = "2026-05-01T23:06:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6a/afa095c5987868fbda27c0f731146ac8e3d07b357adfa83daccaee5b1a16/ty-0.0.34-py3-none-win_amd64.whl", hash = "sha256:1f543968accb952705134028d1fda8656882787dbbc667ad4d6c3ba23791d604", size = 11462526, upload-time = "2026-05-01T23:06:28.514Z" }, + { url = "https://files.pythonhosted.org/packages/63/8f/bf041a06260d77662c0605e56dacfe90b786bf824cbe1aed238d15fe5e84/ty-0.0.34-py3-none-win_arm64.whl", hash = "sha256:ea09108cbcb16b6b06d7596312b433bf49681e78d30e4dc7fb3c1b248a95e09a", size = 10846945, upload-time = "2026-05-01T23:06:44.428Z" }, +] + [[package]] name = "typer" version = "0.24.2"