From 42e6dfa40d428c81cd1dd724a7e6cb463f3f63b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Brand=C3=A9ho?= Date: Tue, 28 Jan 2025 22:11:05 +0100 Subject: [PATCH] enable PGH, bump pyright and fix all #type: ignore (#4699) * enable PGH, bump pyright and fix all #type: ignore * relock poetry file * ignore incompatible override * fix varop tests * ignore missing imports * fix * fix stuff * fix tests * rechange tests * relock with poetry 2.0 --- .pre-commit-config.yaml | 2 +- .../test_benchmark_compile_components.py | 20 +- benchmarks/test_benchmark_compile_pages.py | 26 +-- poetry.lock | 192 ++++-------------- pyproject.toml | 7 +- reflex/__init__.pyi | 2 +- reflex/app.py | 6 +- reflex/app_mixins/lifespan.py | 10 +- reflex/app_mixins/middleware.py | 12 +- reflex/base.py | 12 +- reflex/compiler/utils.py | 6 +- reflex/components/base/bare.py | 2 +- reflex/components/base/meta.py | 4 +- reflex/components/component.py | 18 +- reflex/components/core/banner.py | 8 +- reflex/components/core/cond.py | 17 +- reflex/components/core/debounce.py | 2 +- reflex/components/core/match.py | 8 +- reflex/components/core/upload.py | 2 +- reflex/components/datadisplay/code.py | 2 +- reflex/components/datadisplay/dataeditor.py | 6 +- .../datadisplay/shiki_code_block.py | 11 +- reflex/components/el/constants/reflex.py | 2 +- reflex/components/el/elements/forms.py | 4 +- reflex/components/markdown/markdown.py | 10 +- reflex/components/moment/moment.py | 4 +- reflex/components/next/link.py | 2 +- reflex/components/plotly/plotly.py | 8 +- reflex/components/props.py | 4 +- reflex/components/radix/__init__.pyi | 2 +- reflex/components/radix/primitives/drawer.py | 2 +- .../components/radix/primitives/progress.py | 2 +- reflex/components/radix/primitives/slider.py | 2 +- reflex/components/radix/themes/color_mode.py | 4 +- .../radix/themes/components/radio_group.py | 2 +- .../radix/themes/components/text_field.py | 2 +- .../radix/themes/layout/__init__.pyi | 2 +- reflex/components/radix/themes/layout/list.py | 2 +- .../components/radix/themes/layout/stack.py | 4 +- .../radix/themes/typography/link.py | 2 +- .../radix/themes/typography/text.py | 4 +- .../components/react_player/react_player.py | 2 +- reflex/components/recharts/charts.py | 22 +- reflex/components/recharts/polar.py | 2 +- reflex/components/sonner/toast.py | 8 +- reflex/components/tags/iter_tag.py | 6 +- reflex/config.py | 6 +- reflex/custom_components/custom_components.py | 2 +- reflex/event.py | 50 ++--- reflex/experimental/client_state.py | 4 +- reflex/experimental/layout.py | 10 +- reflex/model.py | 4 +- reflex/reflex.py | 4 +- reflex/state.py | 28 +-- reflex/style.py | 2 +- reflex/testing.py | 36 ++-- reflex/utils/compat.py | 8 +- reflex/utils/console.py | 6 +- reflex/utils/exec.py | 26 ++- reflex/utils/format.py | 10 +- reflex/utils/imports.py | 2 +- reflex/utils/prerequisites.py | 10 +- reflex/utils/processes.py | 8 +- reflex/utils/pyi_generator.py | 36 ++-- reflex/utils/serializers.py | 2 +- reflex/utils/types.py | 26 ++- reflex/vars/base.py | 56 ++--- reflex/vars/datetime.py | 8 +- reflex/vars/function.py | 4 +- reflex/vars/number.py | 34 ++-- reflex/vars/object.py | 12 +- reflex/vars/sequence.py | 34 ++-- tests/integration/test_background_task.py | 10 +- tests/integration/test_component_state.py | 6 +- tests/integration/test_connection_banner.py | 2 +- tests/integration/test_deploy_url.py | 2 +- tests/integration/test_dynamic_routes.py | 22 +- tests/integration/test_event_actions.py | 30 +-- tests/integration/test_event_chain.py | 46 ++--- tests/integration/test_exception_handlers.py | 4 +- tests/integration/test_input.py | 4 +- tests/integration/test_lifespan.py | 6 +- tests/integration/test_login_flow.py | 4 +- tests/integration/test_media.py | 4 +- tests/integration/test_state_inheritance.py | 12 +- tests/integration/test_upload.py | 8 +- tests/integration/test_var_operations.py | 60 +++--- .../tests_playwright/test_appearance.py | 8 +- .../test_datetime_operations.py | 2 +- .../tests_playwright/test_link_hover.py | 2 +- tests/units/compiler/test_compiler.py | 10 +- tests/units/components/core/test_colors.py | 24 +-- tests/units/components/core/test_cond.py | 8 +- tests/units/components/core/test_html.py | 6 +- tests/units/components/core/test_match.py | 4 +- tests/units/components/core/test_upload.py | 10 +- .../units/components/datadisplay/test_code.py | 2 +- .../components/datadisplay/test_datatable.py | 6 +- .../components/datadisplay/test_shiki_code.py | 10 +- tests/units/components/forms/test_form.py | 2 +- tests/units/components/media/test_image.py | 12 +- tests/units/components/test_component.py | 52 ++--- .../components/typography/test_markdown.py | 10 +- tests/units/conftest.py | 10 +- tests/units/states/mutation.py | 2 +- tests/units/test_app.py | 66 +++--- tests/units/test_config.py | 4 +- tests/units/test_event.py | 8 +- tests/units/test_health_endpoint.py | 4 +- tests/units/test_model.py | 14 +- tests/units/test_prerequisites.py | 2 +- tests/units/test_sqlalchemy.py | 8 +- tests/units/test_state.py | 114 +++++------ tests/units/test_style.py | 8 +- tests/units/test_var.py | 12 +- tests/units/utils/test_format.py | 6 +- tests/units/utils/test_utils.py | 6 +- 117 files changed, 731 insertions(+), 828 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 54d8f3d7213..dbe069ae8fb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,7 +28,7 @@ repos: entry: python3 scripts/make_pyi.py - repo: https://github.com/RobertCraigie/pyright-python - rev: v1.1.334 + rev: v1.1.392 hooks: - id: pyright args: [reflex, tests] diff --git a/benchmarks/test_benchmark_compile_components.py b/benchmarks/test_benchmark_compile_components.py index ba7e9c57151..9bcfbf85bbc 100644 --- a/benchmarks/test_benchmark_compile_components.py +++ b/benchmarks/test_benchmark_compile_components.py @@ -34,13 +34,13 @@ def render_component(num: int): rx.box( rx.accordion.root( rx.accordion.item( - header="Full Ingredients", # type: ignore - content="Yes. It's built with accessibility in mind.", # type: ignore + header="Full Ingredients", + content="Yes. It's built with accessibility in mind.", font_size="3em", ), rx.accordion.item( - header="Applications", # type: ignore - content="Yes. It's unstyled by default, giving you freedom over the look and feel.", # type: ignore + header="Applications", + content="Yes. It's unstyled by default, giving you freedom over the look and feel.", ), collapsible=True, variant="ghost", @@ -166,9 +166,9 @@ def app_with_10_components( root=root, app_source=functools.partial( AppWithTenComponentsOnePage, - render_component=render_component, # type: ignore + render_component=render_component, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.fixture(scope="session") @@ -189,9 +189,9 @@ def app_with_100_components( root=root, app_source=functools.partial( AppWithHundredComponentOnePage, - render_component=render_component, # type: ignore + render_component=render_component, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.fixture(scope="session") @@ -212,9 +212,9 @@ def app_with_1000_components( root=root, app_source=functools.partial( AppWithThousandComponentsOnePage, - render_component=render_component, # type: ignore + render_component=render_component, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.mark.skipif(constants.IS_WINDOWS, reason=WINDOWS_SKIP_REASON) diff --git a/benchmarks/test_benchmark_compile_pages.py b/benchmarks/test_benchmark_compile_pages.py index a5c85810ede..149fc613007 100644 --- a/benchmarks/test_benchmark_compile_pages.py +++ b/benchmarks/test_benchmark_compile_pages.py @@ -28,7 +28,7 @@ def render_multiple_pages(app, num: int): """ from typing import Tuple - from rxconfig import config # type: ignore + from rxconfig import config # pyright: ignore [reportMissingImports] import reflex as rx @@ -74,13 +74,13 @@ class State(rx.State): rx.select( ["C", "PF", "SF", "PG", "SG"], placeholder="Select a position. (All)", - on_change=State.set_position, # type: ignore + on_change=State.set_position, # pyright: ignore [reportAttributeAccessIssue] size="3", ), rx.select( college, placeholder="Select a college. (All)", - on_change=State.set_college, # type: ignore + on_change=State.set_college, # pyright: ignore [reportAttributeAccessIssue] size="3", ), ), @@ -95,7 +95,7 @@ class State(rx.State): default_value=[18, 50], min=18, max=50, - on_value_commit=State.set_age, # type: ignore + on_value_commit=State.set_age, # pyright: ignore [reportAttributeAccessIssue] ), align_items="left", width="100%", @@ -110,7 +110,7 @@ class State(rx.State): default_value=[0, 25000000], min=0, max=25000000, - on_value_commit=State.set_salary, # type: ignore + on_value_commit=State.set_salary, # pyright: ignore [reportAttributeAccessIssue] ), align_items="left", width="100%", @@ -130,7 +130,7 @@ class State(rx.State): def AppWithOnePage(): """A reflex app with one page.""" - from rxconfig import config # type: ignore + from rxconfig import config # pyright: ignore [reportMissingImports] import reflex as rx @@ -232,7 +232,7 @@ def app_with_ten_pages( root=root, app_source=functools.partial( AppWithTenPages, - render_comp=render_multiple_pages, # type: ignore + render_comp=render_multiple_pages, # pyright: ignore [reportCallIssue] ), ) @@ -255,9 +255,9 @@ def app_with_hundred_pages( root=root, app_source=functools.partial( AppWithHundredPages, - render_comp=render_multiple_pages, # type: ignore + render_comp=render_multiple_pages, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.fixture(scope="session") @@ -278,9 +278,9 @@ def app_with_thousand_pages( root=root, app_source=functools.partial( AppWithThousandPages, - render_comp=render_multiple_pages, # type: ignore + render_comp=render_multiple_pages, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.fixture(scope="session") @@ -301,9 +301,9 @@ def app_with_ten_thousand_pages( root=root, app_source=functools.partial( AppWithTenThousandPages, - render_comp=render_multiple_pages, # type: ignore + render_comp=render_multiple_pages, # pyright: ignore [reportCallIssue] ), - ) # type: ignore + ) @pytest.mark.skipif(constants.IS_WINDOWS, reason=WINDOWS_SKIP_REASON) diff --git a/poetry.lock b/poetry.lock index 68e8e37db9f..f8d4cf949b2 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 2.0.0 and should not be changed by hand. +# This file is automatically @generated by Poetry 2.0.1 and should not be changed by hand. [[package]] name = "alembic" @@ -86,15 +86,15 @@ files = [ [[package]] name = "attrs" -version = "24.3.0" +version = "25.1.0" description = "Classes Without Boilerplate" optional = false python-versions = ">=3.8" groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "attrs-24.3.0-py3-none-any.whl", hash = "sha256:ac96cd038792094f438ad1f6ff80837353805ac950cd2aa0e0625ef19850c308"}, - {file = "attrs-24.3.0.tar.gz", hash = "sha256:8f5c07333d543103541ba7be0e2ce16eeee8130cb0b3f9238ab904ce1e85baff"}, + {file = "attrs-25.1.0-py3-none-any.whl", hash = "sha256:c75a69e28a550a7e93789579c22aa26b0f5b83b75dc4e08fe092980051e1090a"}, + {file = "attrs-25.1.0.tar.gz", hash = "sha256:1c97078a80c814273a76b2a298a932eb681c87415c11dee0a6921de7f1b02c3e"}, ] [package.extras] @@ -620,25 +620,25 @@ test = ["pytest (>=6)"] [[package]] name = "fastapi" -version = "0.115.6" +version = "0.115.7" description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" optional = false python-versions = ">=3.8" groups = ["main"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "fastapi-0.115.6-py3-none-any.whl", hash = "sha256:e9240b29e36fa8f4bb7290316988e90c381e5092e0cbe84e7818cc3713bcf305"}, - {file = "fastapi-0.115.6.tar.gz", hash = "sha256:9ec46f7addc14ea472958a96aae5b5de65f39721a46aaf5705c480d9a8b76654"}, + {file = "fastapi-0.115.7-py3-none-any.whl", hash = "sha256:eb6a8c8bf7f26009e8147111ff15b5177a0e19bb4a45bc3486ab14804539d21e"}, + {file = "fastapi-0.115.7.tar.gz", hash = "sha256:0f106da6c01d88a6786b3248fb4d7a940d071f6f488488898ad5d354b25ed015"}, ] [package.dependencies] pydantic = ">=1.7.4,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0 || >2.0.0,<2.0.1 || >2.0.1,<2.1.0 || >2.1.0,<3.0.0" -starlette = ">=0.40.0,<0.42.0" +starlette = ">=0.40.0,<0.46.0" typing-extensions = ">=4.8.0" [package.extras] -all = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.5)", "httpx (>=0.23.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=2.11.2)", "orjson (>=3.2.1)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.7)", "pyyaml (>=5.3.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0)", "uvicorn[standard] (>=0.12.0)"] -standard = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.5)", "httpx (>=0.23.0)", "jinja2 (>=2.11.2)", "python-multipart (>=0.0.7)", "uvicorn[standard] (>=0.12.0)"] +all = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.5)", "httpx (>=0.23.0)", "itsdangerous (>=1.1.0)", "jinja2 (>=3.1.5)", "orjson (>=3.2.1)", "pydantic-extra-types (>=2.0.0)", "pydantic-settings (>=2.0.0)", "python-multipart (>=0.0.18)", "pyyaml (>=5.3.1)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0)", "uvicorn[standard] (>=0.12.0)"] +standard = ["email-validator (>=2.0.0)", "fastapi-cli[standard] (>=0.0.5)", "httpx (>=0.23.0)", "jinja2 (>=3.1.5)", "python-multipart (>=0.0.18)", "uvicorn[standard] (>=0.12.0)"] [[package]] name = "filelock" @@ -740,7 +740,7 @@ files = [ {file = "greenlet-3.1.1-cp39-cp39-win_amd64.whl", hash = "sha256:3319aa75e0e0639bc15ff54ca327e8dc7a6fe404003496e3c6925cd3142e0e22"}, {file = "greenlet-3.1.1.tar.gz", hash = "sha256:4ce3ac6cdb6adf7946475d7ef31777c26d94bccc377e070a7986bd2d5c515467"}, ] -markers = {main = "python_version < \"3.14\" and (platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\") and (python_version <= \"3.11\" or python_version >= \"3.12\")", dev = "python_version <= \"3.11\" or python_version >= \"3.12\""} +markers = {main = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\") and python_version < \"3.14\"", dev = "python_version <= \"3.11\" or python_version >= \"3.12\""} [package.extras] docs = ["Sphinx", "furo"] @@ -1540,39 +1540,6 @@ tests = ["check-manifest", "coverage (>=7.4.2)", "defusedxml", "markdown2", "ole typing = ["typing-extensions"] xmp = ["defusedxml"] -[[package]] -name = "pip" -version = "24.3.1" -description = "The PyPA recommended tool for installing Python packages." -optional = false -python-versions = ">=3.8" -groups = ["main"] -markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" -files = [ - {file = "pip-24.3.1-py3-none-any.whl", hash = "sha256:3790624780082365f47549d032f3770eeb2b1e8bd1f7b2e02dace1afa361b4ed"}, - {file = "pip-24.3.1.tar.gz", hash = "sha256:ebcb60557f2aefabc2e0f918751cd24ea0d56d8ec5445fe1807f1d2109660b99"}, -] - -[[package]] -name = "pipdeptree" -version = "2.16.2" -description = "Command line utility to show dependency tree of packages." -optional = false -python-versions = ">=3.8" -groups = ["main"] -markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" -files = [ - {file = "pipdeptree-2.16.2-py3-none-any.whl", hash = "sha256:4b60a20f632aa3449880141d1cd0bc99cb5f93ed46d54d689fd1c9b95f0e53d0"}, - {file = "pipdeptree-2.16.2.tar.gz", hash = "sha256:96ecde8e6f40c95998491a385e4af56d387f94ff7d3b8f209aa34982a721bc43"}, -] - -[package.dependencies] -pip = ">=23.1.2" - -[package.extras] -graphviz = ["graphviz (>=0.20.1)"] -test = ["covdefaults (>=2.3)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "virtualenv (>=20.25,<21)"] - [[package]] name = "platformdirs" version = "4.3.6" @@ -1727,15 +1694,15 @@ markers = {main = "(platform_machine != \"ppc64le\" and platform_machine != \"s3 [[package]] name = "pydantic" -version = "2.10.5" +version = "2.10.6" description = "Data validation using Python type hints" optional = false python-versions = ">=3.8" groups = ["main"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "pydantic-2.10.5-py3-none-any.whl", hash = "sha256:4dd4e322dbe55472cb7ca7e73f4b63574eecccf2835ffa2af9021ce113c83c53"}, - {file = "pydantic-2.10.5.tar.gz", hash = "sha256:278b38dbbaec562011d659ee05f63346951b3a248a6f3642e1bc68894ea2b4ff"}, + {file = "pydantic-2.10.6-py3-none-any.whl", hash = "sha256:427d664bf0b8a2b34ff5dd0f5a18df00591adcee7198fbd71981054cef37b584"}, + {file = "pydantic-2.10.6.tar.gz", hash = "sha256:ca5daa827cce33de7a42be142548b0096bf05a7e7b365aebfa5f8eeec7128236"}, ] [package.dependencies] @@ -1911,23 +1878,25 @@ files = [ [[package]] name = "pyright" -version = "1.1.334" +version = "1.1.392.post0" description = "Command line wrapper for pyright" optional = false python-versions = ">=3.7" groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "pyright-1.1.334-py3-none-any.whl", hash = "sha256:dcb13e8358e021189672c4d6ebcad192ab061e4c7225036973ec493183c6da68"}, - {file = "pyright-1.1.334.tar.gz", hash = "sha256:3adaf10f1f4209575dc022f9c897f7ef024639b7ea5b3cbe49302147e6949cd4"}, + {file = "pyright-1.1.392.post0-py3-none-any.whl", hash = "sha256:252f84458a46fa2f0fd4e2f91fc74f50b9ca52c757062e93f6c250c0d8329eb2"}, + {file = "pyright-1.1.392.post0.tar.gz", hash = "sha256:3b7f88de74a28dcfa90c7d90c782b6569a48c2be5f9d4add38472bdaac247ebd"}, ] [package.dependencies] nodeenv = ">=1.6.0" +typing-extensions = ">=4.1" [package.extras] -all = ["twine (>=3.4.1)"] +all = ["nodejs-wheel-binaries", "twine (>=3.4.1)"] dev = ["twine (>=3.4.1)"] +nodejs = ["nodejs-wheel-binaries"] [[package]] name = "pysocks" @@ -1969,15 +1938,15 @@ dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "pygments [[package]] name = "pytest-asyncio" -version = "0.25.2" +version = "0.25.3" description = "Pytest support for asyncio" optional = false python-versions = ">=3.9" groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "pytest_asyncio-0.25.2-py3-none-any.whl", hash = "sha256:0d0bb693f7b99da304a0634afc0a4b19e49d5e0de2d670f38dc4bfa5727c5075"}, - {file = "pytest_asyncio-0.25.2.tar.gz", hash = "sha256:3f8ef9a98f45948ea91a0ed3dc4268b5326c0e7bce73892acc654df4262ad45f"}, + {file = "pytest_asyncio-0.25.3-py3-none-any.whl", hash = "sha256:9e89518e0f9bd08928f97a3482fdc4e244df17529460bc038291ccaf8f85c7c3"}, + {file = "pytest_asyncio-0.25.3.tar.gz", hash = "sha256:fc1da2cf9f125ada7e710b4ddad05518d4cee187ae9412e9ac9271003497f07a"}, ] [package.dependencies] @@ -2093,7 +2062,7 @@ version = "2.9.0.post0" description = "Extensions to the standard Python datetime module" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["main", "dev"] +groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"}, @@ -2311,29 +2280,26 @@ ocsp = ["cryptography (>=36.0.1)", "pyopenssl (==23.2.1)", "requests (>=2.31.0)" [[package]] name = "reflex-hosting-cli" -version = "0.1.32" +version = "0.1.33" description = "Reflex Hosting CLI" optional = false -python-versions = "<4.0,>=3.8" +python-versions = "<4.0,>=3.9" groups = ["main"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "reflex_hosting_cli-0.1.32-py3-none-any.whl", hash = "sha256:86b4222f3e99d949a209be7de8c457ededebc1f12a721ee6669c6c35fdecc508"}, - {file = "reflex_hosting_cli-0.1.32.tar.gz", hash = "sha256:0b8e4b4b30d9261bf6d720265f1c428b2840bb630896e60a1a2faa095901ed59"}, + {file = "reflex_hosting_cli-0.1.33-py3-none-any.whl", hash = "sha256:3fe72fc448a231c61de4ac646f42c936c70e91330f616a23aec658f905d53bc4"}, + {file = "reflex_hosting_cli-0.1.33.tar.gz", hash = "sha256:81c4a896b106eea99f1cab53ea23a6e19802592ce0468cc38d93d440bc95263a"}, ] [package.dependencies] charset-normalizer = ">=3.3.2,<4.0.0" httpx = ">=0.25.1,<1.0" -pipdeptree = ">=2.13.1,<2.17.0" platformdirs = ">=3.10.0,<5.0" pydantic = ">=1.10.2,<3.0" -python-dateutil = ">=2.8.1" pyyaml = ">=6.0.2,<7.0.0" rich = ">=13.0.0,<14.0" tabulate = ">=0.9.0,<0.10.0" typer = ">=0.15.0,<1" -websockets = ">=10.4" [[package]] name = "requests" @@ -2459,15 +2425,15 @@ jeepney = ">=0.6" [[package]] name = "selenium" -version = "4.28.0" +version = "4.28.1" description = "Official Python bindings for Selenium WebDriver" optional = false python-versions = ">=3.9" groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "selenium-4.28.0-py3-none-any.whl", hash = "sha256:3d6a2e8e1b850a1078884ea19f4e011ecdc12263434d87a0b78769836fb82dd8"}, - {file = "selenium-4.28.0.tar.gz", hash = "sha256:a9fae6eef48d470a1b0c6e45185d96f0dafb025e8da4b346cc41e4da3ac54fa0"}, + {file = "selenium-4.28.1-py3-none-any.whl", hash = "sha256:4238847e45e24e4472cfcf3554427512c7aab9443396435b1623ef406fff1cc1"}, + {file = "selenium-4.28.1.tar.gz", hash = "sha256:0072d08670d7ec32db901bd0107695a330cecac9f196e3afb3fa8163026e022a"}, ] [package.dependencies] @@ -2539,7 +2505,7 @@ version = "1.17.0" description = "Python 2 and 3 compatibility utilities" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" -groups = ["main", "dev"] +groups = ["dev"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}, @@ -2688,22 +2654,22 @@ SQLAlchemy = ">=2.0.14,<2.1.0" [[package]] name = "starlette" -version = "0.41.3" +version = "0.45.3" description = "The little ASGI library that shines." optional = false -python-versions = ">=3.8" +python-versions = ">=3.9" groups = ["main"] markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "starlette-0.41.3-py3-none-any.whl", hash = "sha256:44cedb2b7c77a9de33a8b74b2b90e9f50d11fcf25d8270ea525ad71a25374ff7"}, - {file = "starlette-0.41.3.tar.gz", hash = "sha256:0e4ab3d16522a255be6b28260b938eae2482f98ce5cc934cb08dce8dc3ba5835"}, + {file = "starlette-0.45.3-py3-none-any.whl", hash = "sha256:dfb6d332576f136ec740296c7e8bb8c8a7125044e7c6da30744718880cdd059d"}, + {file = "starlette-0.45.3.tar.gz", hash = "sha256:2cbcba2a75806f8a41c722141486f37c28e30a0921c5f6fe4346cb0dcee1302f"}, ] [package.dependencies] -anyio = ">=3.4.0,<5" +anyio = ">=3.6.2,<5" [package.extras] -full = ["httpx (>=0.22.0)", "itsdangerous", "jinja2", "python-multipart (>=0.0.7)", "pyyaml"] +full = ["httpx (>=0.27.0,<0.29.0)", "itsdangerous", "jinja2", "python-multipart (>=0.0.18)", "pyyaml"] [[package]] name = "starlette-admin" @@ -3040,86 +3006,6 @@ docs = ["Sphinx (>=6.0)", "myst-parser (>=2.0.0)", "sphinx-rtd-theme (>=1.1.0)"] optional = ["python-socks", "wsaccel"] test = ["websockets"] -[[package]] -name = "websockets" -version = "14.2" -description = "An implementation of the WebSocket Protocol (RFC 6455 & 7692)" -optional = false -python-versions = ">=3.9" -groups = ["main"] -markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" -files = [ - {file = "websockets-14.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e8179f95323b9ab1c11723e5d91a89403903f7b001828161b480a7810b334885"}, - {file = "websockets-14.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0d8c3e2cdb38f31d8bd7d9d28908005f6fa9def3324edb9bf336d7e4266fd397"}, - {file = "websockets-14.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:714a9b682deb4339d39ffa674f7b674230227d981a37d5d174a4a83e3978a610"}, - {file = "websockets-14.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2e53c72052f2596fb792a7acd9704cbc549bf70fcde8a99e899311455974ca3"}, - {file = "websockets-14.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e3fbd68850c837e57373d95c8fe352203a512b6e49eaae4c2f4088ef8cf21980"}, - {file = "websockets-14.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b27ece32f63150c268593d5fdb82819584831a83a3f5809b7521df0685cd5d8"}, - {file = "websockets-14.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4daa0faea5424d8713142b33825fff03c736f781690d90652d2c8b053345b0e7"}, - {file = "websockets-14.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:bc63cee8596a6ec84d9753fd0fcfa0452ee12f317afe4beae6b157f0070c6c7f"}, - {file = "websockets-14.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7a570862c325af2111343cc9b0257b7119b904823c675b22d4ac547163088d0d"}, - {file = "websockets-14.2-cp310-cp310-win32.whl", hash = "sha256:75862126b3d2d505e895893e3deac0a9339ce750bd27b4ba515f008b5acf832d"}, - {file = "websockets-14.2-cp310-cp310-win_amd64.whl", hash = "sha256:cc45afb9c9b2dc0852d5c8b5321759cf825f82a31bfaf506b65bf4668c96f8b2"}, - {file = "websockets-14.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3bdc8c692c866ce5fefcaf07d2b55c91d6922ac397e031ef9b774e5b9ea42166"}, - {file = "websockets-14.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c93215fac5dadc63e51bcc6dceca72e72267c11def401d6668622b47675b097f"}, - {file = "websockets-14.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1c9b6535c0e2cf8a6bf938064fb754aaceb1e6a4a51a80d884cd5db569886910"}, - {file = "websockets-14.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a52a6d7cf6938e04e9dceb949d35fbdf58ac14deea26e685ab6368e73744e4c"}, - {file = "websockets-14.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9f05702e93203a6ff5226e21d9b40c037761b2cfb637187c9802c10f58e40473"}, - {file = "websockets-14.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22441c81a6748a53bfcb98951d58d1af0661ab47a536af08920d129b4d1c3473"}, - {file = "websockets-14.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd9b868d78b194790e6236d9cbc46d68aba4b75b22497eb4ab64fa640c3af56"}, - {file = "websockets-14.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1a5a20d5843886d34ff8c57424cc65a1deda4375729cbca4cb6b3353f3ce4142"}, - {file = "websockets-14.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:34277a29f5303d54ec6468fb525d99c99938607bc96b8d72d675dee2b9f5bf1d"}, - {file = "websockets-14.2-cp311-cp311-win32.whl", hash = "sha256:02687db35dbc7d25fd541a602b5f8e451a238ffa033030b172ff86a93cb5dc2a"}, - {file = "websockets-14.2-cp311-cp311-win_amd64.whl", hash = "sha256:862e9967b46c07d4dcd2532e9e8e3c2825e004ffbf91a5ef9dde519ee2effb0b"}, - {file = "websockets-14.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1f20522e624d7ffbdbe259c6b6a65d73c895045f76a93719aa10cd93b3de100c"}, - {file = "websockets-14.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:647b573f7d3ada919fd60e64d533409a79dcf1ea21daeb4542d1d996519ca967"}, - {file = "websockets-14.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6af99a38e49f66be5a64b1e890208ad026cda49355661549c507152113049990"}, - {file = "websockets-14.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:091ab63dfc8cea748cc22c1db2814eadb77ccbf82829bac6b2fbe3401d548eda"}, - {file = "websockets-14.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b374e8953ad477d17e4851cdc66d83fdc2db88d9e73abf755c94510ebddceb95"}, - {file = "websockets-14.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a39d7eceeea35db85b85e1169011bb4321c32e673920ae9c1b6e0978590012a3"}, - {file = "websockets-14.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0a6f3efd47ffd0d12080594f434faf1cd2549b31e54870b8470b28cc1d3817d9"}, - {file = "websockets-14.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:065ce275e7c4ffb42cb738dd6b20726ac26ac9ad0a2a48e33ca632351a737267"}, - {file = "websockets-14.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e9d0e53530ba7b8b5e389c02282f9d2aa47581514bd6049d3a7cffe1385cf5fe"}, - {file = "websockets-14.2-cp312-cp312-win32.whl", hash = "sha256:20e6dd0984d7ca3037afcb4494e48c74ffb51e8013cac71cf607fffe11df7205"}, - {file = "websockets-14.2-cp312-cp312-win_amd64.whl", hash = "sha256:44bba1a956c2c9d268bdcdf234d5e5ff4c9b6dc3e300545cbe99af59dda9dcce"}, - {file = "websockets-14.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6f1372e511c7409a542291bce92d6c83320e02c9cf392223272287ce55bc224e"}, - {file = "websockets-14.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4da98b72009836179bb596a92297b1a61bb5a830c0e483a7d0766d45070a08ad"}, - {file = "websockets-14.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8a86a269759026d2bde227652b87be79f8a734e582debf64c9d302faa1e9f03"}, - {file = "websockets-14.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:86cf1aaeca909bf6815ea714d5c5736c8d6dd3a13770e885aafe062ecbd04f1f"}, - {file = "websockets-14.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9b0f6c3ba3b1240f602ebb3971d45b02cc12bd1845466dd783496b3b05783a5"}, - {file = "websockets-14.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:669c3e101c246aa85bc8534e495952e2ca208bd87994650b90a23d745902db9a"}, - {file = "websockets-14.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:eabdb28b972f3729348e632ab08f2a7b616c7e53d5414c12108c29972e655b20"}, - {file = "websockets-14.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2066dc4cbcc19f32c12a5a0e8cc1b7ac734e5b64ac0a325ff8353451c4b15ef2"}, - {file = "websockets-14.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ab95d357cd471df61873dadf66dd05dd4709cae001dd6342edafc8dc6382f307"}, - {file = "websockets-14.2-cp313-cp313-win32.whl", hash = "sha256:a9e72fb63e5f3feacdcf5b4ff53199ec8c18d66e325c34ee4c551ca748623bbc"}, - {file = "websockets-14.2-cp313-cp313-win_amd64.whl", hash = "sha256:b439ea828c4ba99bb3176dc8d9b933392a2413c0f6b149fdcba48393f573377f"}, - {file = "websockets-14.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:7cd5706caec1686c5d233bc76243ff64b1c0dc445339bd538f30547e787c11fe"}, - {file = "websockets-14.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ec607328ce95a2f12b595f7ae4c5d71bf502212bddcea528290b35c286932b12"}, - {file = "websockets-14.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:da85651270c6bfb630136423037dd4975199e5d4114cae6d3066641adcc9d1c7"}, - {file = "websockets-14.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c3ecadc7ce90accf39903815697917643f5b7cfb73c96702318a096c00aa71f5"}, - {file = "websockets-14.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1979bee04af6a78608024bad6dfcc0cc930ce819f9e10342a29a05b5320355d0"}, - {file = "websockets-14.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2dddacad58e2614a24938a50b85969d56f88e620e3f897b7d80ac0d8a5800258"}, - {file = "websockets-14.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:89a71173caaf75fa71a09a5f614f450ba3ec84ad9fca47cb2422a860676716f0"}, - {file = "websockets-14.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:6af6a4b26eea4fc06c6818a6b962a952441e0e39548b44773502761ded8cc1d4"}, - {file = "websockets-14.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:80c8efa38957f20bba0117b48737993643204645e9ec45512579132508477cfc"}, - {file = "websockets-14.2-cp39-cp39-win32.whl", hash = "sha256:2e20c5f517e2163d76e2729104abc42639c41cf91f7b1839295be43302713661"}, - {file = "websockets-14.2-cp39-cp39-win_amd64.whl", hash = "sha256:b4c8cef610e8d7c70dea92e62b6814a8cd24fbd01d7103cc89308d2bfe1659ef"}, - {file = "websockets-14.2-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:d7d9cafbccba46e768be8a8ad4635fa3eae1ffac4c6e7cb4eb276ba41297ed29"}, - {file = "websockets-14.2-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:c76193c1c044bd1e9b3316dcc34b174bbf9664598791e6fb606d8d29000e070c"}, - {file = "websockets-14.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fd475a974d5352390baf865309fe37dec6831aafc3014ffac1eea99e84e83fc2"}, - {file = "websockets-14.2-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2c6c0097a41968b2e2b54ed3424739aab0b762ca92af2379f152c1aef0187e1c"}, - {file = "websockets-14.2-pp310-pypy310_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6d7ff794c8b36bc402f2e07c0b2ceb4a2424147ed4785ff03e2a7af03711d60a"}, - {file = "websockets-14.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:dec254fcabc7bd488dab64846f588fc5b6fe0d78f641180030f8ea27b76d72c3"}, - {file = "websockets-14.2-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:bbe03eb853e17fd5b15448328b4ec7fb2407d45fb0245036d06a3af251f8e48f"}, - {file = "websockets-14.2-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:a3c4aa3428b904d5404a0ed85f3644d37e2cb25996b7f096d77caeb0e96a3b42"}, - {file = "websockets-14.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:577a4cebf1ceaf0b65ffc42c54856214165fb8ceeba3935852fc33f6b0c55e7f"}, - {file = "websockets-14.2-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ad1c1d02357b7665e700eca43a31d52814ad9ad9b89b58118bdabc365454b574"}, - {file = "websockets-14.2-pp39-pypy39_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f390024a47d904613577df83ba700bd189eedc09c57af0a904e5c39624621270"}, - {file = "websockets-14.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:3c1426c021c38cf92b453cdf371228d3430acd775edee6bac5a4d577efc72365"}, - {file = "websockets-14.2-py3-none-any.whl", hash = "sha256:7a6ceec4ea84469f15cf15807a747e9efe57e369c384fa86e022b3bea679b79b"}, - {file = "websockets-14.2.tar.gz", hash = "sha256:5059ed9c54945efb321f097084b4c7e52c246f2c869815876a69d1efc4ad6eb5"}, -] - [[package]] name = "wheel" version = "0.45.1" @@ -3266,4 +3152,4 @@ type = ["pytest-mypy"] [metadata] lock-version = "2.1" python-versions = ">=3.10, <4.0" -content-hash = "376707066a00c43aef555c6db2ccb0ddfde0ee9011e8f20110d728fb723f1662" +content-hash = "35c503a68e87896b4f7d7c209dd3fe6d707ebcc1702377cab0a1339554c6ad77" diff --git a/pyproject.toml b/pyproject.toml index d19d1a0ac2c..761f9e2c99a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,7 +55,7 @@ typing_extensions = ">=4.6.0" [tool.poetry.group.dev.dependencies] pytest = ">=7.1.2,<9.0" pytest-mock = ">=3.10.0,<4.0" -pyright = ">=1.1.229,<1.1.335" +pyright = ">=1.1.392, <1.2" darglint = ">=1.8.1,<2.0" dill = ">=0.3.8" toml = ">=0.10.2,<1.0" @@ -80,12 +80,13 @@ requires = ["poetry-core>=1.5.1"] build-backend = "poetry.core.masonry.api" [tool.pyright] +reportIncompatibleMethodOverride = false [tool.ruff] target-version = "py310" output-format = "concise" lint.isort.split-on-trailing-comma = false -lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "N", "PERF", "PTH", "RUF", "SIM", "T", "TRY", "W"] +lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "N", "PERF", "PGH", "PTH", "RUF", "SIM", "T", "TRY", "W"] lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012", "TRY0"] lint.pydocstyle.convention = "google" @@ -94,7 +95,7 @@ lint.pydocstyle.convention = "google" "tests/*.py" = ["D100", "D103", "D104", "B018", "PERF", "T", "N"] "benchmarks/*.py" = ["D100", "D103", "D104", "B018", "PERF", "T", "N"] "reflex/.templates/*.py" = ["D100", "D103", "D104"] -"*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N"] +"*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N", "PGH"] "pyi_generator.py" = ["N802"] "reflex/constants/*.py" = ["N"] "*/blank.py" = ["I001"] diff --git a/reflex/__init__.pyi b/reflex/__init__.pyi index 1f9b4ecd80e..5c80269adba 100644 --- a/reflex/__init__.pyi +++ b/reflex/__init__.pyi @@ -131,7 +131,7 @@ from .components.radix.themes.layout.container import container as container from .components.radix.themes.layout.flex import flex as flex from .components.radix.themes.layout.grid import grid as grid from .components.radix.themes.layout.list import list_item as list_item -from .components.radix.themes.layout.list import list_ns as list # noqa +from .components.radix.themes.layout.list import list_ns as list # noqa: F401 from .components.radix.themes.layout.list import ordered_list as ordered_list from .components.radix.themes.layout.list import unordered_list as unordered_list from .components.radix.themes.layout.section import section as section diff --git a/reflex/app.py b/reflex/app.py index 20c01cba6f4..e3b45e7b2b3 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -146,7 +146,7 @@ def default_backend_exception_handler(exception: Exception) -> EventSpec: position="top-center", id="backend_error", style={"width": "500px"}, - ) # type: ignore + ) # pyright: ignore [reportReturnType] else: error_message.insert(0, "An error occurred.") return window_alert("\n".join(error_message)) @@ -780,7 +780,7 @@ def _get_frontend_packages(self, imports: Dict[str, set[ImportVar]]): frontend_packages = get_config().frontend_packages _frontend_packages = [] for package in frontend_packages: - if package in (get_config().tailwind or {}).get("plugins", []): # type: ignore + if package in (get_config().tailwind or {}).get("plugins", []): console.warn( f"Tailwind packages are inferred from 'plugins', remove `{package}` from `frontend_packages`" ) @@ -1025,7 +1025,7 @@ def get_compilation_time() -> str: compiler.compile_document_root( self.head_components, html_lang=self.html_lang, - html_custom_attrs=self.html_custom_attrs, # type: ignore + html_custom_attrs=self.html_custom_attrs, # pyright: ignore [reportArgumentType] ) ) diff --git a/reflex/app_mixins/lifespan.py b/reflex/app_mixins/lifespan.py index 9403e0f3502..8bdef2eb99d 100644 --- a/reflex/app_mixins/lifespan.py +++ b/reflex/app_mixins/lifespan.py @@ -32,7 +32,7 @@ async def _run_lifespan_tasks(self, app: FastAPI): try: async with contextlib.AsyncExitStack() as stack: for task in self.lifespan_tasks: - run_msg = f"Started lifespan task: {task.__name__} as {{type}}" # type: ignore + run_msg = f"Started lifespan task: {task.__name__} as {{type}}" # pyright: ignore [reportAttributeAccessIssue] if isinstance(task, asyncio.Task): running_tasks.append(task) else: @@ -73,7 +73,7 @@ def register_lifespan_task(self, task: Callable | asyncio.Task, **task_kwargs): if task_kwargs: original_task = task - task = functools.partial(task, **task_kwargs) # type: ignore - functools.update_wrapper(task, original_task) # type: ignore - self.lifespan_tasks.add(task) # type: ignore - console.debug(f"Registered lifespan task: {task.__name__}") # type: ignore + task = functools.partial(task, **task_kwargs) # pyright: ignore [reportArgumentType] + functools.update_wrapper(task, original_task) # pyright: ignore [reportArgumentType] + self.lifespan_tasks.add(task) + console.debug(f"Registered lifespan task: {task.__name__}") # pyright: ignore [reportAttributeAccessIssue] diff --git a/reflex/app_mixins/middleware.py b/reflex/app_mixins/middleware.py index 30593d9aec3..c81fd7806d4 100644 --- a/reflex/app_mixins/middleware.py +++ b/reflex/app_mixins/middleware.py @@ -53,11 +53,11 @@ async def _preprocess(self, state: BaseState, event: Event) -> StateUpdate | Non """ for middleware in self.middleware: if asyncio.iscoroutinefunction(middleware.preprocess): - out = await middleware.preprocess(app=self, state=state, event=event) # type: ignore + out = await middleware.preprocess(app=self, state=state, event=event) # pyright: ignore [reportArgumentType] else: - out = middleware.preprocess(app=self, state=state, event=event) # type: ignore + out = middleware.preprocess(app=self, state=state, event=event) # pyright: ignore [reportArgumentType] if out is not None: - return out # type: ignore + return out # pyright: ignore [reportReturnType] async def _postprocess( self, state: BaseState, event: Event, update: StateUpdate @@ -78,18 +78,18 @@ async def _postprocess( for middleware in self.middleware: if asyncio.iscoroutinefunction(middleware.postprocess): out = await middleware.postprocess( - app=self, # type: ignore + app=self, # pyright: ignore [reportArgumentType] state=state, event=event, update=update, ) else: out = middleware.postprocess( - app=self, # type: ignore + app=self, # pyright: ignore [reportArgumentType] state=state, event=event, update=update, ) if out is not None: - return out # type: ignore + return out # pyright: ignore [reportReturnType] return update diff --git a/reflex/base.py b/reflex/base.py index a88e557ef47..5c01808128a 100644 --- a/reflex/base.py +++ b/reflex/base.py @@ -13,7 +13,7 @@ if not TYPE_CHECKING: import pydantic.main as pydantic_main from pydantic import BaseModel - from pydantic.fields import ModelField # type: ignore + from pydantic.fields import ModelField def validate_field_name(bases: List[Type["BaseModel"]], field_name: str) -> None: @@ -44,13 +44,13 @@ def validate_field_name(bases: List[Type["BaseModel"]], field_name: str) -> None # monkeypatch pydantic validate_field_name method to skip validating # shadowed state vars when reloading app via utils.prerequisites.get_app(reload=True) -pydantic_main.validate_field_name = validate_field_name # type: ignore +pydantic_main.validate_field_name = validate_field_name # pyright: ignore [reportPossiblyUnboundVariable, reportPrivateImportUsage] if TYPE_CHECKING: from reflex.vars import Var -class Base(BaseModel): # pyright: ignore [reportUnboundVariable] +class Base(BaseModel): # pyright: ignore [reportPossiblyUnboundVariable] """The base class subclassed by all Reflex classes. This class wraps Pydantic and provides common methods such as @@ -75,7 +75,7 @@ def json(self) -> str: """ from reflex.utils.serializers import serialize - return self.__config__.json_dumps( # type: ignore + return self.__config__.json_dumps( self.dict(), default=serialize, ) @@ -113,12 +113,12 @@ def add_field(cls, var: Var, default_value: Any): default_value: The default value of the field """ var_name = var._var_field_name - new_field = ModelField.infer( + new_field = ModelField.infer( # pyright: ignore [reportPossiblyUnboundVariable] name=var_name, value=default_value, annotation=var._var_type, class_validators=None, - config=cls.__config__, # type: ignore + config=cls.__config__, ) cls.__fields__.update({var_name: new_field}) diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index c0ba28f4b36..02692e43b8b 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -12,7 +12,9 @@ try: from pydantic.v1.fields import ModelField except ModuleNotFoundError: - from pydantic.fields import ModelField # type: ignore + from pydantic.fields import ( + ModelField, # pyright: ignore [reportAttributeAccessIssue] + ) from reflex import constants from reflex.components.base import ( @@ -115,7 +117,7 @@ def compile_imports(import_dict: ParsedImportDict) -> list[dict]: default, rest = compile_import_statement(fields) # prevent lib from being rendered on the page if all imports are non rendered kind - if not any(f.render for f in fields): # type: ignore + if not any(f.render for f in fields): continue if not lib: diff --git a/reflex/components/base/bare.py b/reflex/components/base/bare.py index e576fac8596..0f0bef8b9a7 100644 --- a/reflex/components/base/bare.py +++ b/reflex/components/base/bare.py @@ -31,7 +31,7 @@ def create(cls, contents: Any) -> Component: return cls(contents=contents) else: contents = str(contents) if contents is not None else "" - return cls(contents=contents) # type: ignore + return cls(contents=contents) def _get_all_hooks_internal(self) -> dict[str, VarData | None]: """Include the hooks for the component. diff --git a/reflex/components/base/meta.py b/reflex/components/base/meta.py index 526233c8b3a..10264009e68 100644 --- a/reflex/components/base/meta.py +++ b/reflex/components/base/meta.py @@ -53,11 +53,11 @@ class Description(Meta): """A component that displays the title of the current page.""" # The type of the description. - name: str = "description" + name: str | None = "description" class Image(Meta): """A component that displays the title of the current page.""" # The type of the image. - property: str = "og:image" + property: str | None = "og:image" diff --git a/reflex/components/component.py b/reflex/components/component.py index 58bdfe7c295..c8833091834 100644 --- a/reflex/components/component.py +++ b/reflex/components/component.py @@ -150,7 +150,7 @@ def _get_all_refs(self) -> set[str]: class ComponentNamespace(SimpleNamespace): """A namespace to manage components with subcomponents.""" - def __hash__(self) -> int: + def __hash__(self) -> int: # pyright: ignore [reportIncompatibleVariableOverride] """Get the hash of the namespace. Returns: @@ -462,9 +462,7 @@ def determine_key(value): if types.is_union(passed_type): # We need to check all possible types in the union. passed_types = ( - arg - for arg in passed_type.__args__ # type: ignore - if arg is not type(None) + arg for arg in passed_type.__args__ if arg is not type(None) ) if ( # If the passed var is a union, check if all possible types are valid. @@ -491,7 +489,7 @@ def determine_key(value): # Check if the key is an event trigger. if key in component_specific_triggers: kwargs["event_triggers"][key] = EventChain.create( - value=value, # type: ignore + value=value, args_spec=component_specific_triggers[key], key=key, ) @@ -578,7 +576,7 @@ def get_event_triggers( annotation = field.annotation if (metadata := getattr(annotation, "__metadata__", None)) is not None: args_spec = metadata[0] - default_triggers[field.name] = args_spec or (no_args_event_spec) # type: ignore + default_triggers[field.name] = args_spec or (no_args_event_spec) return default_triggers def __repr__(self) -> str: @@ -761,7 +759,7 @@ def _add_style(self) -> Style: # Walk the MRO to call all `add_style` methods. for base in self._iter_parent_classes_with_method("add_style"): - s = base.add_style(self) # type: ignore + s = base.add_style(self) if s is not None: styles.append(s) @@ -1674,7 +1672,7 @@ def __init__(self, *args, **kwargs): if base_value is not None and isinstance(value, Component): self.component_props[key] = value value = base_value._replace( - merge_var_data=VarData( # type: ignore + merge_var_data=VarData( imports=value._get_all_imports(), hooks=value._get_all_hooks(), ) @@ -1707,7 +1705,7 @@ def __hash__(self) -> int: return hash(self.tag) @classmethod - def get_props(cls) -> Set[str]: + def get_props(cls) -> Set[str]: # pyright: ignore [reportIncompatibleVariableOverride] """Get the props for the component. Returns: @@ -1802,7 +1800,7 @@ def _get_vars( include_children=include_children, ignore_ids=ignore_ids ) - @lru_cache(maxsize=None) # noqa + @lru_cache(maxsize=None) # noqa: B019 def get_component(self) -> Component: """Render the component. diff --git a/reflex/components/core/banner.py b/reflex/components/core/banner.py index b7b6fae6c84..6479bf3b2ce 100644 --- a/reflex/components/core/banner.py +++ b/reflex/components/core/banner.py @@ -25,7 +25,7 @@ from reflex.vars.number import BooleanVar from reflex.vars.sequence import LiteralArrayVar -connect_error_var_data: VarData = VarData( # type: ignore +connect_error_var_data: VarData = VarData( imports=Imports.EVENTS, hooks={Hooks.EVENTS: None}, ) @@ -99,14 +99,14 @@ def add_hooks(self) -> list[str | Var]: """ toast_id = "websocket-error" target_url = WebsocketTargetURL.create() - props = ToastProps( # type: ignore + props = ToastProps( description=LiteralVar.create( f"Check if server is reachable at {target_url}", ), close_button=True, duration=120000, id=toast_id, - ) + ) # pyright: ignore [reportCallIssue] individual_hooks = [ f"const toast_props = {LiteralVar.create(props)!s};", @@ -116,7 +116,7 @@ def add_hooks(self) -> list[str | Var]: _var_data=VarData( imports={ "react": ["useEffect", "useState"], - **dict(target_url._get_all_var_data().imports), # type: ignore + **dict(target_url._get_all_var_data().imports), # pyright: ignore [reportArgumentType, reportOptionalMemberAccess] } ), ).call( diff --git a/reflex/components/core/cond.py b/reflex/components/core/cond.py index 488990f543b..25b691808dd 100644 --- a/reflex/components/core/cond.py +++ b/reflex/components/core/cond.py @@ -26,10 +26,9 @@ class Cond(MemoizationLeaf): cond: Var[Any] # The component to render if the cond is true. - comp1: BaseComponent = None # type: ignore - + comp1: BaseComponent | None = None # The component to render if the cond is false. - comp2: BaseComponent = None # type: ignore + comp2: BaseComponent | None = None @classmethod def create( @@ -73,8 +72,8 @@ def _get_props_imports(self): def _render(self) -> Tag: return CondTag( cond=self.cond, - true_value=self.comp1.render(), - false_value=self.comp2.render(), + true_value=self.comp1.render(), # pyright: ignore [reportOptionalMemberAccess] + false_value=self.comp2.render(), # pyright: ignore [reportOptionalMemberAccess] ) def render(self) -> Dict: @@ -111,7 +110,7 @@ def add_imports(self) -> ImportDict: @overload -def cond(condition: Any, c1: Component, c2: Any) -> Component: ... +def cond(condition: Any, c1: Component, c2: Any) -> Component: ... # pyright: ignore [reportOverlappingOverload] @overload @@ -163,16 +162,16 @@ def create_var(cond_part): # Create the conditional var. return ternary_operation( - cond_var.bool()._replace( # type: ignore + cond_var.bool()._replace( merge_var_data=VarData(imports=_IS_TRUE_IMPORT), - ), # type: ignore + ), c1, c2, ) @overload -def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # type: ignore +def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # pyright: ignore [reportOverlappingOverload] @overload diff --git a/reflex/components/core/debounce.py b/reflex/components/core/debounce.py index 12cc94426fc..1d798994d88 100644 --- a/reflex/components/core/debounce.py +++ b/reflex/components/core/debounce.py @@ -28,7 +28,7 @@ class DebounceInput(Component): min_length: Var[int] # Time to wait between end of input and triggering on_change - debounce_timeout: Var[int] = DEFAULT_DEBOUNCE_TIMEOUT # type: ignore + debounce_timeout: Var[int] = Var.create(DEFAULT_DEBOUNCE_TIMEOUT) # If true, notify when Enter key is pressed force_notify_by_enter: Var[bool] diff --git a/reflex/components/core/match.py b/reflex/components/core/match.py index 8b9382c8998..ae8568ac571 100644 --- a/reflex/components/core/match.py +++ b/reflex/components/core/match.py @@ -222,7 +222,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], # type: ignore + children=[case[-1] for case in match_cases] + [default], # pyright: ignore [reportArgumentType] ) ) @@ -236,13 +236,13 @@ def _create_match_cond_var_or_component( _js_expr=format.format_match( cond=str(match_cond_var), match_cases=match_cases, - default=default, # type: ignore + default=default, # pyright: ignore [reportArgumentType] ), - _var_type=default._var_type, # type: ignore + _var_type=default._var_type, # pyright: ignore [reportAttributeAccessIssue,reportOptionalMemberAccess] _var_data=VarData.merge( match_cond_var._get_all_var_data(), *[el._get_all_var_data() for case in match_cases for el in case], - default._get_all_var_data(), # type: ignore + default._get_all_var_data(), # pyright: ignore [reportAttributeAccessIssue, reportOptionalMemberAccess] ), ) diff --git a/reflex/components/core/upload.py b/reflex/components/core/upload.py index 4666a8f1bad..897b89608c4 100644 --- a/reflex/components/core/upload.py +++ b/reflex/components/core/upload.py @@ -269,7 +269,7 @@ def create(cls, *children, **props) -> Component: on_drop = upload_props["on_drop"] if isinstance(on_drop, Callable): # Call the lambda to get the event chain. - on_drop = call_event_fn(on_drop, _on_drop_spec) # type: ignore + on_drop = call_event_fn(on_drop, _on_drop_spec) if isinstance(on_drop, EventSpec): # Update the provided args for direct use with on_drop. on_drop = on_drop.with_args( diff --git a/reflex/components/datadisplay/code.py b/reflex/components/datadisplay/code.py index 242e812b2be..4f1eb493e38 100644 --- a/reflex/components/datadisplay/code.py +++ b/reflex/components/datadisplay/code.py @@ -449,7 +449,7 @@ def create( if can_copy: code = children[0] - copy_button = ( # type: ignore + copy_button = ( copy_button if copy_button is not None else Button.create( diff --git a/reflex/components/datadisplay/dataeditor.py b/reflex/components/datadisplay/dataeditor.py index f71f9771394..b2d6417bdb6 100644 --- a/reflex/components/datadisplay/dataeditor.py +++ b/reflex/components/datadisplay/dataeditor.py @@ -165,7 +165,7 @@ class DataEditor(NoSSRComponent): tag = "DataEditor" is_default = True - library: str = "@glideapps/glide-data-grid@^6.0.3" + library: str | None = "@glideapps/glide-data-grid@^6.0.3" lib_dependencies: List[str] = [ "lodash@^4.17.21", "react-responsive-carousel@^3.2.7", @@ -321,6 +321,8 @@ def add_imports(self) -> ImportDict: Returns: The import dict. """ + if self.library is None: + return {} return { "": f"{format.format_library_name(self.library)}/dist/index.css", self.library: "GridCellKind", @@ -343,7 +345,7 @@ def add_hooks(self) -> list[str]: data_callback = self.get_cell_content._js_expr else: data_callback = f"getData_{editor_id}" - self.get_cell_content = Var(_js_expr=data_callback) # type: ignore + self.get_cell_content = Var(_js_expr=data_callback) code = [f"function {data_callback}([col, row])" "{"] diff --git a/reflex/components/datadisplay/shiki_code_block.py b/reflex/components/datadisplay/shiki_code_block.py index 3b6bce8a1f8..2d30409669c 100644 --- a/reflex/components/datadisplay/shiki_code_block.py +++ b/reflex/components/datadisplay/shiki_code_block.py @@ -602,7 +602,7 @@ def create( transformer_styles = {} # Collect styles from transformers and wrapper - for transformer in code_block.transformers._var_value: # type: ignore + for transformer in code_block.transformers._var_value: # pyright: ignore [reportAttributeAccessIssue] if isinstance(transformer, ShikiBaseTransformers) and transformer.style: transformer_styles.update(transformer.style) transformer_styles.update(code_wrapper_props.pop("style", {})) @@ -653,8 +653,9 @@ def create_transformer(cls, library: str, fns: list[str]) -> ShikiBaseTransforme raise ValueError( f"the function names should be str names of functions in the specified transformer: {library!r}" ) - return ShikiBaseTransformers( # type: ignore - library=library, fns=[FunctionStringVar.create(fn) for fn in fns] + return ShikiBaseTransformers( + library=library, + fns=[FunctionStringVar.create(fn) for fn in fns], # pyright: ignore [reportCallIssue] ) def _render(self, props: dict[str, Any] | None = None): @@ -757,13 +758,13 @@ def create( if can_copy: code = children[0] - copy_button = ( # type: ignore + copy_button = ( copy_button if copy_button is not None else Button.create( Icon.create(tag="copy", size=16, color=color("gray", 11)), on_click=[ - set_clipboard(cls._strip_transformer_triggers(code)), # type: ignore + set_clipboard(cls._strip_transformer_triggers(code)), copy_script(), ], style=Style( diff --git a/reflex/components/el/constants/reflex.py b/reflex/components/el/constants/reflex.py index 05c29832587..199edf569c9 100644 --- a/reflex/components/el/constants/reflex.py +++ b/reflex/components/el/constants/reflex.py @@ -48,4 +48,4 @@ def attr_to_prop(attr_name: str) -> str: ELEMENT_TO_PROPS = defaultdict(list) for prop, elements in PROP_TO_ELEMENTS.items(): for el in elements: - ELEMENT_TO_PROPS[el].append(prop) # type: ignore + ELEMENT_TO_PROPS[el].append(prop) diff --git a/reflex/components/el/elements/forms.py b/reflex/components/el/elements/forms.py index 3e22357214f..51ad201b2b4 100644 --- a/reflex/components/el/elements/forms.py +++ b/reflex/components/el/elements/forms.py @@ -153,7 +153,7 @@ class Form(BaseHTML): target: Var[Union[str, int, bool]] # If true, the form will be cleared after submit. - reset_on_submit: Var[bool] = False # type: ignore + reset_on_submit: Var[bool] = Var.create(False) # The name used to make this form's submit handler function unique. handle_submit_unique_name: Var[str] @@ -405,7 +405,7 @@ def create(cls, *children, **props): (value_var := Var.create(value))._var_type ): props["value"] = ternary_operation( - (value_var != Var.create(None)) # pyright: ignore [reportGeneralTypeIssues] + (value_var != Var.create(None)) # pyright: ignore [reportArgumentType] & (value_var != Var(_js_expr="undefined")), value, Var.create(""), diff --git a/reflex/components/markdown/markdown.py b/reflex/components/markdown/markdown.py index 7c65c0d4342..686c49a6458 100644 --- a/reflex/components/markdown/markdown.py +++ b/reflex/components/markdown/markdown.py @@ -65,8 +65,8 @@ def get_base_component_map() -> dict[str, Callable]: "h5": lambda value: Heading.create(value, as_="h5", size="2", margin_y="0.5em"), "h6": lambda value: Heading.create(value, as_="h6", size="1", margin_y="0.5em"), "p": lambda value: Text.create(value, margin_y="1em"), - "ul": lambda value: UnorderedList.create(value, margin_y="1em"), # type: ignore - "ol": lambda value: OrderedList.create(value, margin_y="1em"), # type: ignore + "ul": lambda value: UnorderedList.create(value, margin_y="1em"), + "ol": lambda value: OrderedList.create(value, margin_y="1em"), "li": lambda value: ListItem.create(value, margin_y="0.5em"), "a": lambda value: Link.create(value), "code": lambda value: Code.create(value), @@ -236,7 +236,7 @@ def add_imports(self) -> ImportDict | list[ImportDict]: ), }, *[ - component(_MOCK_ARG)._get_all_imports() # type: ignore + component(_MOCK_ARG)._get_all_imports() for component in self.component_map.values() ], ] @@ -327,7 +327,7 @@ def get_component(self, tag: str, **props) -> Component: if tag != "codeblock" # For codeblock, the mapping for some cases returns an array of elements. Let's join them into a string. else ternary_operation( - ARRAY_ISARRAY.call(_CHILDREN), # type: ignore + ARRAY_ISARRAY.call(_CHILDREN), # pyright: ignore [reportArgumentType] _CHILDREN.to(list).join("\n"), _CHILDREN, ).to(str) @@ -425,7 +425,7 @@ def _get_custom_code(self) -> str | None: for _component in self.component_map.values(): comp = _component(_MOCK_ARG) hooks.update(comp._get_all_hooks()) - formatted_hooks = MACROS.module.renderHooks(hooks) # type: ignore + formatted_hooks = MACROS.module.renderHooks(hooks) # pyright: ignore [reportAttributeAccessIssue] return f""" function {self._get_component_map_name()} () {{ {formatted_hooks} diff --git a/reflex/components/moment/moment.py b/reflex/components/moment/moment.py index 80940d228ae..a5fe79f07d1 100644 --- a/reflex/components/moment/moment.py +++ b/reflex/components/moment/moment.py @@ -28,9 +28,9 @@ class MomentDelta: class Moment(NoSSRComponent): """The Moment component.""" - tag: str = "Moment" + tag: str | None = "Moment" is_default = True - library: str = "react-moment" + library: str | None = "react-moment" lib_dependencies: List[str] = ["moment"] # How often the date update (how often time update / 0 to disable). diff --git a/reflex/components/next/link.py b/reflex/components/next/link.py index 0f7c8129608..187618a09e1 100644 --- a/reflex/components/next/link.py +++ b/reflex/components/next/link.py @@ -17,4 +17,4 @@ class NextLink(Component): href: Var[str] # Whether to pass the href prop to the child. - pass_href: Var[bool] = True # type: ignore + pass_href: Var[bool] = Var.create(True) diff --git a/reflex/components/plotly/plotly.py b/reflex/components/plotly/plotly.py index 68efd45451b..c85423d35b2 100644 --- a/reflex/components/plotly/plotly.py +++ b/reflex/components/plotly/plotly.py @@ -18,8 +18,8 @@ Template = layout.Template except ImportError: console.warn("Plotly is not installed. Please run `pip install plotly`.") - Figure = Any # type: ignore - Template = Any # type: ignore + Figure = Any + Template = Any def _event_points_data_signature(e0: Var) -> Tuple[Var[List[Point]]]: @@ -102,13 +102,13 @@ class Plotly(NoSSRComponent): is_default = True # The figure to display. This can be a plotly figure or a plotly data json. - data: Var[Figure] # type: ignore + data: Var[Figure] # pyright: ignore [reportInvalidTypeForm] # The layout of the graph. layout: Var[Dict] # The template for visual appearance of the graph. - template: Var[Template] # type: ignore + template: Var[Template] # pyright: ignore [reportInvalidTypeForm] # The config of the graph. config: Var[Dict] diff --git a/reflex/components/props.py b/reflex/components/props.py index adce134fcd6..8230364069e 100644 --- a/reflex/components/props.py +++ b/reflex/components/props.py @@ -62,13 +62,13 @@ def __init__(self, component_name=None, **kwargs): try: super().__init__(**kwargs) except ValidationError as e: - invalid_fields = ", ".join([error["loc"][0] for error in e.errors()]) # type: ignore + invalid_fields = ", ".join([error["loc"][0] for error in e.errors()]) # pyright: ignore [reportCallIssue, reportArgumentType] supported_props_str = ", ".join(f'"{field}"' for field in self.get_fields()) raise InvalidPropValueError( f"Invalid prop(s) {invalid_fields} for {component_name!r}. Supported props are {supported_props_str}" ) from None - class Config: + class Config: # pyright: ignore [reportIncompatibleVariableOverride] """Pydantic config.""" arbitrary_types_allowed = True diff --git a/reflex/components/radix/__init__.pyi b/reflex/components/radix/__init__.pyi index f4e81666a8e..9a16627b5ae 100644 --- a/reflex/components/radix/__init__.pyi +++ b/reflex/components/radix/__init__.pyi @@ -55,7 +55,7 @@ from .themes.layout.container import container as container from .themes.layout.flex import flex as flex from .themes.layout.grid import grid as grid from .themes.layout.list import list_item as list_item -from .themes.layout.list import list_ns as list # noqa +from .themes.layout.list import list_ns as list # noqa: F401 from .themes.layout.list import ordered_list as ordered_list from .themes.layout.list import unordered_list as unordered_list from .themes.layout.section import section as section diff --git a/reflex/components/radix/primitives/drawer.py b/reflex/components/radix/primitives/drawer.py index 534b97ac108..b9056c9d0d4 100644 --- a/reflex/components/radix/primitives/drawer.py +++ b/reflex/components/radix/primitives/drawer.py @@ -83,7 +83,7 @@ class DrawerTrigger(DrawerComponent): alias = "Vaul" + tag # Defaults to true, if the first child acts as the trigger. - as_child: Var[bool] = True # type: ignore + as_child: Var[bool] = Var.create(True) @classmethod def create(cls, *children: Any, **props: Any) -> Component: diff --git a/reflex/components/radix/primitives/progress.py b/reflex/components/radix/primitives/progress.py index 72aee1038aa..5fcc52f1b20 100644 --- a/reflex/components/radix/primitives/progress.py +++ b/reflex/components/radix/primitives/progress.py @@ -83,7 +83,7 @@ def add_style(self) -> dict[str, Any] | None: "&[data_state='loading']": { "transition": f"transform {DEFAULT_ANIMATION_DURATION}ms linear", }, - "transform": f"translateX(calc(-100% + ({self.value} / {self.max} * 100%)))", # type: ignore + "transform": f"translateX(calc(-100% + ({self.value} / {self.max} * 100%)))", "boxShadow": "inset 0 0 0 1px var(--gray-a5)", } diff --git a/reflex/components/radix/primitives/slider.py b/reflex/components/radix/primitives/slider.py index 68f39e32c26..6136e3171ac 100644 --- a/reflex/components/radix/primitives/slider.py +++ b/reflex/components/radix/primitives/slider.py @@ -30,7 +30,7 @@ def on_value_event_spec( Returns: The event handler spec. """ - return (value,) # type: ignore + return (value,) class SliderRoot(SliderComponent): diff --git a/reflex/components/radix/themes/color_mode.py b/reflex/components/radix/themes/color_mode.py index e93a26ef6a3..2377a2422dd 100644 --- a/reflex/components/radix/themes/color_mode.py +++ b/reflex/components/radix/themes/color_mode.py @@ -115,12 +115,12 @@ def create( Returns: The button component. """ - position = props.pop("position", None) + position: str | Var = props.pop("position", None) allow_system = props.pop("allow_system", False) # position is used to set nice defaults for positioning the icon button if isinstance(position, Var): - _set_var_default(props, position, "position", "fixed", position) # type: ignore + _set_var_default(props, position, "position", "fixed", position) # pyright: ignore [reportArgumentType] _set_var_default(props, position, "bottom", "2rem") _set_var_default(props, position, "top", "2rem") _set_var_default(props, position, "left", "2rem") diff --git a/reflex/components/radix/themes/components/radio_group.py b/reflex/components/radix/themes/components/radio_group.py index 80b3ee10cba..f34c92159f4 100644 --- a/reflex/components/radix/themes/components/radio_group.py +++ b/reflex/components/radix/themes/components/radio_group.py @@ -155,7 +155,7 @@ def create( if isinstance(default_value, str) or ( isinstance(default_value, Var) and default_value._var_type is str ): - default_value = LiteralVar.create(default_value) # type: ignore + default_value = LiteralVar.create(default_value) else: default_value = LiteralVar.create(default_value).to_string() diff --git a/reflex/components/radix/themes/components/text_field.py b/reflex/components/radix/themes/components/text_field.py index c8bdab44356..130fb7aed34 100644 --- a/reflex/components/radix/themes/components/text_field.py +++ b/reflex/components/radix/themes/components/text_field.py @@ -105,7 +105,7 @@ def create(cls, *children, **props) -> Component: (value_var := Var.create(value))._var_type ): props["value"] = ternary_operation( - (value_var != Var.create(None)) # pyright: ignore [reportGeneralTypeIssues] + (value_var != Var.create(None)) # pyright: ignore [reportArgumentType] & (value_var != Var(_js_expr="undefined")), value, Var.create(""), diff --git a/reflex/components/radix/themes/layout/__init__.pyi b/reflex/components/radix/themes/layout/__init__.pyi index 6712a306844..21fc8d921e8 100644 --- a/reflex/components/radix/themes/layout/__init__.pyi +++ b/reflex/components/radix/themes/layout/__init__.pyi @@ -9,7 +9,7 @@ from .container import container as container from .flex import flex as flex from .grid import grid as grid from .list import list_item as list_item -from .list import list_ns as list # noqa +from .list import list_ns as list # noqa: F401 from .list import ordered_list as ordered_list from .list import unordered_list as unordered_list from .section import section as section diff --git a/reflex/components/radix/themes/layout/list.py b/reflex/components/radix/themes/layout/list.py index a306e19a490..b79e99bf778 100644 --- a/reflex/components/radix/themes/layout/list.py +++ b/reflex/components/radix/themes/layout/list.py @@ -72,7 +72,7 @@ def create( if isinstance(items, Var): children = [Foreach.create(items, ListItem.create)] else: - children = [ListItem.create(item) for item in items] # type: ignore + children = [ListItem.create(item) for item in items] props["direction"] = "column" style = props.setdefault("style", {}) style["list_style_type"] = list_style_type diff --git a/reflex/components/radix/themes/layout/stack.py b/reflex/components/radix/themes/layout/stack.py index d11c3488bc1..f017ff783f4 100644 --- a/reflex/components/radix/themes/layout/stack.py +++ b/reflex/components/radix/themes/layout/stack.py @@ -49,14 +49,14 @@ class VStack(Stack): """A vertical stack component.""" # The direction of the stack. - direction: Var[LiteralFlexDirection] = "column" # type: ignore + direction: Var[LiteralFlexDirection] = Var.create("column") class HStack(Stack): """A horizontal stack component.""" # The direction of the stack. - direction: Var[LiteralFlexDirection] = "row" # type: ignore + direction: Var[LiteralFlexDirection] = Var.create("row") stack = Stack.create diff --git a/reflex/components/radix/themes/typography/link.py b/reflex/components/radix/themes/typography/link.py index c931024084c..09172b10831 100644 --- a/reflex/components/radix/themes/typography/link.py +++ b/reflex/components/radix/themes/typography/link.py @@ -60,7 +60,7 @@ def add_imports(self) -> ImportDict: Returns: The import dict. """ - return next_link._get_imports() # type: ignore + return next_link._get_imports() # pyright: ignore [reportReturnType] @classmethod def create(cls, *children, **props) -> Component: diff --git a/reflex/components/radix/themes/typography/text.py b/reflex/components/radix/themes/typography/text.py index 1663ddedfa5..cb6527915c7 100644 --- a/reflex/components/radix/themes/typography/text.py +++ b/reflex/components/radix/themes/typography/text.py @@ -47,7 +47,7 @@ class Text(elements.Span, RadixThemesComponent, MarkdownComponentMap): as_child: Var[bool] # Change the default rendered element into a semantically appropriate alternative (cannot be used with asChild) - as_: Var[LiteralType] = "p" # type: ignore + as_: Var[LiteralType] = Var.create("p") # Text size: "1" - "9" size: Var[Responsive[LiteralTextSize]] @@ -71,7 +71,7 @@ class Text(elements.Span, RadixThemesComponent, MarkdownComponentMap): class Span(Text): """A variant of text rendering as element.""" - as_: Var[LiteralType] = "span" # type: ignore + as_: Var[LiteralType] = Var.create("span") class Em(elements.Em, RadixThemesComponent): diff --git a/reflex/components/react_player/react_player.py b/reflex/components/react_player/react_player.py index fb0319ceb3d..7b7bb34e3a9 100644 --- a/reflex/components/react_player/react_player.py +++ b/reflex/components/react_player/react_player.py @@ -39,7 +39,7 @@ class ReactPlayer(NoSSRComponent): loop: Var[bool] # Set to true or false to display native player controls. - controls: Var[bool] = True # type: ignore + controls: Var[bool] = Var.create(True) # Set to true to show just the video thumbnail, which loads the full player on click light: Var[bool] diff --git a/reflex/components/recharts/charts.py b/reflex/components/recharts/charts.py index c25107dc057..6edfce58f0c 100644 --- a/reflex/components/recharts/charts.py +++ b/reflex/components/recharts/charts.py @@ -25,10 +25,10 @@ class ChartBase(RechartsCharts): """A component that wraps a Recharts charts.""" # The width of chart container. String or Integer - width: Var[Union[str, int]] = "100%" # type: ignore + width: Var[Union[str, int]] = Var.create("100%") # The height of chart container. - height: Var[Union[str, int]] = "100%" # type: ignore + height: Var[Union[str, int]] = Var.create("100%") # The customized event handler of click on the component in this chart on_click: EventHandler[no_args_event_spec] @@ -84,21 +84,19 @@ def create(cls, *children, **props) -> Component: cls._ensure_valid_dimension("width", width) cls._ensure_valid_dimension("height", height) - dim_props = { - "width": width if width is not None else "100%", - "height": height if height is not None else "100%", - } - # Ensure that the min_height and min_width are set to prevent the chart from collapsing. # We are using small values so that height and width can still be used over min_height and min_width. # Without this, sometimes the chart will not be visible. Causing confusion to the user. # With this, the user will see a small chart and can adjust the height and width and can figure out that the issue is with the size. - dim_props["min_height"] = props.pop("min_height", 10) - dim_props["min_width"] = props.pop("min_width", 10) + min_height = props.pop("min_height", 10) + min_width = props.pop("min_width", 10) return ResponsiveContainer.create( super().create(*children, **props), - **dim_props, # type: ignore + width=width if width is not None else "100%", + height=height if height is not None else "100%", + min_width=min_width, + min_height=min_height, ) @@ -460,10 +458,10 @@ class Treemap(RechartsCharts): alias = "RechartsTreemap" # The width of chart container. String or Integer. Default: "100%" - width: Var[Union[str, int]] = "100%" # type: ignore + width: Var[Union[str, int]] = Var.create("100%") # The height of chart container. String or Integer. Default: "100%" - height: Var[Union[str, int]] = "100%" # type: ignore + height: Var[Union[str, int]] = Var.create("100%") # data of treemap. Array data: Var[List[Dict[str, Any]]] diff --git a/reflex/components/recharts/polar.py b/reflex/components/recharts/polar.py index 7bb623d3491..77aa1ef5eac 100644 --- a/reflex/components/recharts/polar.py +++ b/reflex/components/recharts/polar.py @@ -64,7 +64,7 @@ class Pie(Recharts): legend_type: Var[LiteralLegendType] # If false set, labels will not be drawn. If true set, labels will be drawn which have the props calculated internally. Default: False - label: Var[bool] = False # type: ignore + label: Var[bool] = Var.create(False) # If false set, label lines will not be drawn. If true set, label lines will be drawn which have the props calculated internally. Default: False label_line: Var[bool] diff --git a/reflex/components/sonner/toast.py b/reflex/components/sonner/toast.py index 7177c6473dd..0f666fd6473 100644 --- a/reflex/components/sonner/toast.py +++ b/reflex/components/sonner/toast.py @@ -142,7 +142,7 @@ def dict(self, *args, **kwargs) -> dict[str, Any]: Returns: The object as a dictionary with ToastAction fields intact. """ - kwargs.setdefault("exclude_none", True) # type: ignore + kwargs.setdefault("exclude_none", True) d = super().dict(*args, **kwargs) # Keep these fields as ToastAction so they can be serialized specially if "action" in d: @@ -167,7 +167,7 @@ def dict(self, *args, **kwargs) -> dict[str, Any]: class Toaster(Component): """A Toaster Component for displaying toast notifications.""" - library: str = "sonner@1.7.2" + library: str | None = "sonner@1.7.2" tag = "Toaster" @@ -222,6 +222,8 @@ def add_hooks(self) -> list[Var | str]: Returns: The hooks for the toaster component. """ + if self.library is None: + return [] hook = Var( _js_expr=f"{toast_ref} = toast", _var_data=VarData( @@ -266,7 +268,7 @@ def send_toast( raise ValueError("Toast message or title or description must be provided.") if props: - args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # pyright: ignore [reportCallIssue, reportGeneralTypeIssues] + args = LiteralVar.create(ToastProps(component_name="rx.toast", **props)) # pyright: ignore [reportCallIssue] toast = toast_command.call(message, args) else: toast = toast_command.call(message) diff --git a/reflex/components/tags/iter_tag.py b/reflex/components/tags/iter_tag.py index 38ecaf81c79..cb02ca000df 100644 --- a/reflex/components/tags/iter_tag.py +++ b/reflex/components/tags/iter_tag.py @@ -41,14 +41,14 @@ def get_iterable_var_type(self) -> Type: try: if iterable._var_type.mro()[0] is dict: # Arg is a tuple of (key, value). - return Tuple[get_args(iterable._var_type)] # type: ignore + return Tuple[get_args(iterable._var_type)] # pyright: ignore [reportReturnType] elif iterable._var_type.mro()[0] is tuple: # Arg is a union of any possible values in the tuple. - return Union[get_args(iterable._var_type)] # type: ignore + return Union[get_args(iterable._var_type)] # pyright: ignore [reportReturnType] else: return get_args(iterable._var_type)[0] except Exception: - return Any + return Any # pyright: ignore [reportReturnType] def get_index_var(self) -> Var: """Get the index var for the tag (with curly braces). diff --git a/reflex/config.py b/reflex/config.py index c3c5e4cf5df..a76bf987d47 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -390,7 +390,7 @@ def set(self, value: T | None) -> None: os.environ[self.name] = str(value) -class env_var: # type: ignore # noqa: N801 +class env_var: # noqa: N801 # pyright: ignore [reportRedeclaration] """Descriptor for environment variables.""" name: str @@ -600,7 +600,7 @@ class Config(Base): See the [configuration](https://reflex.dev/docs/getting-started/configuration/) docs for more info. """ - class Config: + class Config: # pyright: ignore [reportIncompatibleVariableOverride] """Pydantic config for the config.""" validate_assignment = True @@ -766,7 +766,7 @@ def update_from_env(self) -> dict[str, Any]: """ if self.env_file: try: - from dotenv import load_dotenv # type: ignore + from dotenv import load_dotenv # pyright: ignore [reportMissingImports] # load env file if exists load_dotenv(self.env_file, override=True) diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py index 8000e7f4c48..3bfbb158066 100644 --- a/reflex/custom_components/custom_components.py +++ b/reflex/custom_components/custom_components.py @@ -925,7 +925,7 @@ def _get_file_from_prompt_in_loop() -> Tuple[bytes, str] | None: image_file = file_extension = None while image_file is None: image_filepath = Path( - console.ask("Upload a preview image of your demo app (enter to skip)") + console.ask("Upload a preview image of your demo app (enter to skip)") # pyright: ignore [reportArgumentType] ) if not image_filepath: break diff --git a/reflex/event.py b/reflex/event.py index 96c2c30b945..0fc874b38d9 100644 --- a/reflex/event.py +++ b/reflex/event.py @@ -263,7 +263,7 @@ class EventSpec(EventActionsMixin): """ # The event handler. - handler: EventHandler = dataclasses.field(default=None) # type: ignore + handler: EventHandler = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] # The handler on the client to process event. client_handler_name: str = dataclasses.field(default="") @@ -589,7 +589,7 @@ def no_args_event_spec() -> Tuple[()]: Returns: An empty tuple. """ - return () # type: ignore + return () # These chains can be used for their side effects when no other events are desired. @@ -617,9 +617,9 @@ def __call__(self, *values: Var[T]) -> Tuple[Var[T], ...]: @overload -def passthrough_event_spec( +def passthrough_event_spec( # pyright: ignore [reportOverlappingOverload] event_type: Type[T], / -) -> Callable[[Var[T]], Tuple[Var[T]]]: ... # type: ignore +) -> Callable[[Var[T]], Tuple[Var[T]]]: ... @overload @@ -632,7 +632,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]: # type: ignore +def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[T]: # pyright: ignore [reportInconsistentOverload] """A helper function that returns the input event as output. Args: @@ -646,9 +646,9 @@ 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] # type: ignore + return_annotation = Tuple[inner_type] - inner.__signature__ = inspect.signature(inner).replace( # type: ignore + inner.__signature__ = inspect.signature(inner).replace( # pyright: ignore [reportFunctionMemberAccess] parameters=[ inspect.Parameter( f"ev_{i}", @@ -730,7 +730,7 @@ def as_event_spec(self, handler: EventHandler) -> EventSpec: # Call the lambda to get the event chain. events = call_event_fn( on_upload_progress, self.on_upload_progress_args_spec - ) # type: ignore + ) else: raise ValueError(f"{on_upload_progress} is not a valid event handler.") if isinstance(events, Var): @@ -777,7 +777,7 @@ def fn(): return None fn.__qualname__ = name - fn.__signature__ = sig + fn.__signature__ = sig # pyright: ignore [reportFunctionMemberAccess] return EventSpec( handler=EventHandler(fn=fn, state_full_name=FRONTEND_EVENT_STATE), args=tuple( @@ -1050,13 +1050,13 @@ def download( is_data_url = (data.js_type() == "string") & ( data.to(str).startswith("data:") - ) # type: ignore + ) # If it's a data: URI, use it as is, otherwise convert the Var to JSON in a data: URI. - url = cond( # type: ignore + url = cond( is_data_url, data.to(str), - "data:text/plain," + data.to_string(), # type: ignore + "data:text/plain," + data.to_string(), ) elif isinstance(data, bytes): # Caller provided bytes, so base64 encode it as a data: URI. @@ -1230,7 +1230,7 @@ def call_event_handler( #noqa: DAR401 """ - event_spec_args = parse_args_spec(event_spec) # type: ignore + event_spec_args = parse_args_spec(event_spec) if isinstance(event_callback, EventSpec): check_fn_match_arg_spec( @@ -1340,7 +1340,7 @@ def call_event_handler( if delayed_exceptions: raise delayed_exceptions[0] - return event_callback(*event_spec_args) # type: ignore + return event_callback(*event_spec_args) def unwrap_var_annotation(annotation: GenericType): @@ -1574,7 +1574,7 @@ def fix_events( if not isinstance(e, EventSpec): raise ValueError(f"Unexpected event type, {type(e)}.") name = format.format_event_handler(e.handler) - payload = {k._js_expr: v._decode() for k, v in e.args} # type: ignore + payload = {k._js_expr: v._decode() for k, v in e.args} # Filter router_data to reduce payload size event_router_data = { @@ -1623,7 +1623,7 @@ class EventVar(ObjectVar, python_types=EventSpec): class LiteralEventVar(VarOperationCall, LiteralVar, EventVar): """A literal event var.""" - _var_value: EventSpec = dataclasses.field(default=None) # type: ignore + _var_value: EventSpec = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] def __hash__(self) -> int: """Get the hash of the var. @@ -1687,7 +1687,7 @@ class EventChainVar(BuilderFunctionVar, python_types=EventChain): class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainVar): """A literal event chain var.""" - _var_value: EventChain = dataclasses.field(default=None) # type: ignore + _var_value: EventChain = dataclasses.field(default=None) # pyright: ignore [reportAssignmentType] def __hash__(self) -> int: """Get the hash of the var. @@ -1717,7 +1717,7 @@ def create( if isinstance(value.args_spec, Sequence) else value.args_spec ) - sig = inspect.signature(arg_spec) # type: ignore + sig = inspect.signature(arg_spec) # pyright: ignore [reportArgumentType] if sig.parameters: arg_def = tuple((f"_{p}" for p in sig.parameters)) arg_def_expr = LiteralVar.create([Var(_js_expr=arg) for arg in arg_def]) @@ -1819,7 +1819,7 @@ def __call__( value4: V4 | Var[V4], ) -> EventCallback[Q, T]: ... - def __call__(self, *values) -> EventCallback: # type: ignore + def __call__(self, *values) -> EventCallback: # pyright: ignore [reportInconsistentOverload] """Call the function with the values. Args: @@ -1828,7 +1828,7 @@ def __call__(self, *values) -> EventCallback: # type: ignore Returns: The function with the values. """ - return self.func(*values) # type: ignore + return self.func(*values) # pyright: ignore [reportCallIssue, reportReturnType] @overload def __get__( @@ -1838,7 +1838,7 @@ def __get__( @overload def __get__(self, instance, owner) -> Callable[P, T]: ... - def __get__(self, instance, owner) -> Callable: # type: ignore + def __get__(self, instance, owner) -> Callable: """Get the function with the instance bound to it. Args: @@ -1849,9 +1849,9 @@ def __get__(self, instance, owner) -> Callable: # type: ignore The function with the instance bound to it """ if instance is None: - return self.func # type: ignore + return self.func - return partial(self.func, instance) # type: ignore + return partial(self.func, instance) G = ParamSpec("G") @@ -1902,7 +1902,7 @@ class EventNamespace(types.SimpleNamespace): @staticmethod def __call__( func: None = None, *, background: bool | None = None - ) -> Callable[[Callable[Concatenate[BASE_STATE, P], T]], EventCallback[P, T]]: ... + ) -> Callable[[Callable[Concatenate[BASE_STATE, P], T]], EventCallback[P, T]]: ... # pyright: ignore [reportInvalidTypeVarUse] @overload @staticmethod @@ -1945,7 +1945,7 @@ def wrapper( "Background task must be async function or generator." ) setattr(func, BACKGROUND_TASK_MARKER, True) - return func # type: ignore + return func # pyright: ignore [reportReturnType] if func is not None: return wrapper(func) diff --git a/reflex/experimental/client_state.py b/reflex/experimental/client_state.py index ca91905aedc..ce3a941bbd1 100644 --- a/reflex/experimental/client_state.py +++ b/reflex/experimental/client_state.py @@ -201,9 +201,7 @@ def value(self) -> Var: ) .to(self._var_type) ._replace( - merge_var_data=VarData( # type: ignore - imports=_refs_import if self._global_ref else {} - ) + merge_var_data=VarData(imports=_refs_import if self._global_ref else {}) ) ) diff --git a/reflex/experimental/layout.py b/reflex/experimental/layout.py index e5a1bab0447..1c74271b2df 100644 --- a/reflex/experimental/layout.py +++ b/reflex/experimental/layout.py @@ -44,10 +44,10 @@ def add_style(self) -> dict[str, Any] | None: Returns: The style of the component. """ - sidebar: Component = self.children[-2] # type: ignore - spacer: Component = self.children[-1] # type: ignore + sidebar: Component = self.children[-2] # pyright: ignore [reportAssignmentType] + spacer: Component = self.children[-1] # pyright: ignore [reportAssignmentType] open = ( - self.State.open # type: ignore + self.State.open # pyright: ignore [reportAttributeAccessIssue] if self.State else Var(_js_expr="open") ) @@ -159,11 +159,11 @@ def create(cls, sidebar: Component, **props): """ trigger_props = {**props, **sidebar_trigger_style} - inner_sidebar: Component = sidebar.children[0] # type: ignore + inner_sidebar: Component = sidebar.children[0] # pyright: ignore [reportAssignmentType] sidebar_width = inner_sidebar.style.get("width") if sidebar.State: - open, toggle = sidebar.State.open, sidebar.State.toggle # type: ignore + open, toggle = sidebar.State.open, sidebar.State.toggle # pyright: ignore [reportAttributeAccessIssue] else: open, toggle = ( Var(_js_expr="open"), diff --git a/reflex/model.py b/reflex/model.py index 295159de048..6e44498e90e 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -242,7 +242,7 @@ def get_metadata(cls) -> sqlalchemy.MetaData: return metadata -class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssues] +class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssues,reportIncompatibleVariableOverride] """Base class to define a table in the database.""" # The primary key for the table. @@ -415,7 +415,7 @@ def run_autogenerate(rev, context): connection=connection, target_metadata=ModelRegistry.get_metadata(), render_item=cls._alembic_render_item, - process_revision_directives=writer, # type: ignore + process_revision_directives=writer, compare_type=False, render_as_batch=True, # for sqlite compatibility ) diff --git a/reflex/reflex.py b/reflex/reflex.py index 34a4a58a58e..2fb10a944ba 100644 --- a/reflex/reflex.py +++ b/reflex/reflex.py @@ -17,7 +17,7 @@ from reflex.utils import console, telemetry # Disable typer+rich integration for help panels -typer.core.rich = None # type: ignore +typer.core.rich = None # pyright: ignore [reportPrivateImportUsage] # Create the app. try: @@ -355,7 +355,7 @@ def logout( check_version() - logout(loglevel) # type: ignore + logout(loglevel) # pyright: ignore [reportArgumentType] db_cli = typer.Typer() diff --git a/reflex/state.py b/reflex/state.py index be3deda78f2..badc40dfd69 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -587,7 +587,7 @@ def __init_subclass__(cls, mixin: bool = False, **kwargs): if cls._item_is_event_handler(name, fn) } - for mixin in cls._mixins(): + for mixin in cls._mixins(): # pyright: ignore [reportAssignmentType] for name, value in mixin.__dict__.items(): if name in cls.inherited_vars: continue @@ -599,7 +599,7 @@ def __init_subclass__(cls, mixin: bool = False, **kwargs): cls.computed_vars[newcv._js_expr] = newcv cls.vars[newcv._js_expr] = newcv continue - if types.is_backend_base_variable(name, mixin): + if types.is_backend_base_variable(name, mixin): # pyright: ignore [reportArgumentType] cls.backend_vars[name] = copy.deepcopy(value) continue if events.get(name) is not None: @@ -899,7 +899,7 @@ def get_parent_state(cls) -> Type[BaseState] | None: ] if len(parent_states) >= 2: raise ValueError(f"Only one parent state is allowed {parent_states}.") - return parent_states[0] if len(parent_states) == 1 else None # type: ignore + return parent_states[0] if len(parent_states) == 1 else None @classmethod def get_substates(cls) -> set[Type[BaseState]]: @@ -1268,8 +1268,8 @@ def __getattribute__(self, name: str) -> Any: fn = _no_chain_background_task(type(self), name, handler.fn) else: fn = functools.partial(handler.fn, self) - fn.__module__ = handler.fn.__module__ # type: ignore - fn.__qualname__ = handler.fn.__qualname__ # type: ignore + fn.__module__ = handler.fn.__module__ + fn.__qualname__ = handler.fn.__qualname__ return fn backend_vars = super().__getattribute__("_backend_vars") @@ -1634,7 +1634,7 @@ async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE: """ # Oopsie case: you didn't give me a Var... so get what you give. if not isinstance(var, Var): - return var # type: ignore + return var # Fast case: this is a literal var and the value is known. if hasattr(var, "_var_value"): @@ -2453,7 +2453,7 @@ def on_load_internal(self) -> list[Event | EventSpec] | None: self.router.session.client_token, router_data=self.router_data, ), - State.set_is_hydrated(True), # type: ignore + State.set_is_hydrated(True), # pyright: ignore [reportAttributeAccessIssue] ] @@ -2737,7 +2737,7 @@ def __getattr__(self, name: str) -> Any: # ensure mutations to these containers are blocked unless proxy is _mutable return ImmutableMutableProxy( wrapped=value.__wrapped__, - state=self, # type: ignore + state=self, field_name=value._self_field_name, ) if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__: @@ -2750,7 +2750,7 @@ def __getattr__(self, name: str) -> Any: ) if isinstance(value, MethodType) and value.__self__ is self.__wrapped__: # Rebind methods to the proxy instance - value = type(value)(value.__func__, self) # type: ignore + value = type(value)(value.__func__, self) return value def __setattr__(self, name: str, value: Any) -> None: @@ -2950,7 +2950,7 @@ class StateManagerMemory(StateManager): # The dict of mutexes for each client _states_locks: Dict[str, asyncio.Lock] = pydantic.PrivateAttr({}) - class Config: + class Config: # pyright: ignore [reportIncompatibleVariableOverride] """The Pydantic config.""" fields = { @@ -3068,7 +3068,7 @@ class StateManagerDisk(StateManager): # The token expiration time (s). token_expiration: int = pydantic.Field(default_factory=_default_token_expiration) - class Config: + class Config: # pyright: ignore [reportIncompatibleVariableOverride] """The Pydantic config.""" fields = { @@ -3776,9 +3776,9 @@ def __new__(cls, wrapped: Any, *args, **kwargs) -> MutableProxy: wrapper_cls_name, (cls,), { - dataclasses._FIELDS: getattr( # pyright: ignore [reportGeneralTypeIssues] + dataclasses._FIELDS: getattr( # pyright: ignore [reportAttributeAccessIssue] wrapped_cls, - dataclasses._FIELDS, # pyright: ignore [reportGeneralTypeIssues] + dataclasses._FIELDS, # pyright: ignore [reportAttributeAccessIssue] ), }, ) @@ -3931,7 +3931,7 @@ def __getattr__(self, __name: str) -> Any: ): # Wrap methods called on Base subclasses, which might do _anything_ return wrapt.FunctionWrapper( - functools.partial(value.__func__, self), + functools.partial(value.__func__, self), # pyright: ignore [reportFunctionMemberAccess] self._wrap_recursive_decorator, ) diff --git a/reflex/style.py b/reflex/style.py index 3916bbc7c16..5142d018177 100644 --- a/reflex/style.py +++ b/reflex/style.py @@ -78,7 +78,7 @@ def set_color_mode( _var_data=VarData.merge( base_setter._get_all_var_data(), new_color_mode._get_all_var_data() ), - ).to(FunctionVar, EventChain) # type: ignore + ).to(FunctionVar, EventChain) # Var resolves to the current color mode for the app ("light", "dark" or "system") diff --git a/reflex/testing.py b/reflex/testing.py index 7c6aab93be7..897cb3424a7 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -80,7 +80,7 @@ TimeoutType = Optional[Union[int, float]] if platform.system() == "Windows": - FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore + FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue] FRONTEND_POPEN_ARGS["shell"] = True else: FRONTEND_POPEN_ARGS["start_new_session"] = True @@ -258,7 +258,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 # type: ignore + self.app_source = self.app_source.func # get the source from a function or module object source_code = "\n".join( [ @@ -294,11 +294,15 @@ def _initialize_app(self): if p not in before_decorated_pages ] self.app_instance = self.app_module.app - if isinstance(self.app_instance._state_manager, StateManagerRedis): + if self.app_instance and isinstance( + self.app_instance._state_manager, StateManagerRedis + ): # Create our own redis connection for testing. - self.state_manager = StateManagerRedis.create(self.app_instance._state) + self.state_manager = StateManagerRedis.create(self.app_instance._state) # pyright: ignore [reportArgumentType] else: - self.state_manager = self.app_instance._state_manager + self.state_manager = ( + self.app_instance._state_manager if self.app_instance else None + ) def _reload_state_module(self): """Reload the rx.State module to avoid conflict when reloading.""" @@ -621,23 +625,23 @@ def frontend( want_headless = True if driver_clz is None: requested_driver = environment.APP_HARNESS_DRIVER.get() - driver_clz = getattr(webdriver, requested_driver) + driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable] if driver_options is None: - driver_options = getattr(webdriver, f"{requested_driver}Options")() - if driver_clz is webdriver.Chrome: + driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable] + if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable] if driver_options is None: - driver_options = webdriver.ChromeOptions() + driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable] driver_options.add_argument("--class=AppHarness") if want_headless: driver_options.add_argument("--headless=new") - elif driver_clz is webdriver.Firefox: + elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable] if driver_options is None: - driver_options = webdriver.FirefoxOptions() + driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable] if want_headless: driver_options.add_argument("-headless") - elif driver_clz is webdriver.Edge: + elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable] if driver_options is None: - driver_options = webdriver.EdgeOptions() + driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable] if want_headless: driver_options.add_argument("headless") if driver_options is None: @@ -653,7 +657,7 @@ def frontend( driver_options.set_capability(key, value) if driver_kwargs is None: driver_kwargs = {} - driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore + driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType] driver.get(self.frontend_url) self._frontends.append(driver) return driver @@ -885,8 +889,8 @@ def finish_request(self, request: socket.socket, client_address: tuple[str, int] request, client_address, self, - directory=str(self.root), # type: ignore - error_page_map=self.error_page_map, # type: ignore + directory=str(self.root), # pyright: ignore [reportCallIssue] + error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue] ) diff --git a/reflex/utils/compat.py b/reflex/utils/compat.py index e63492a6b25..33991106395 100644 --- a/reflex/utils/compat.py +++ b/reflex/utils/compat.py @@ -50,11 +50,11 @@ def pydantic_v1_patch(): ] originals = {module: sys.modules.get(module) for module in patched_modules} try: - import pydantic.v1 # type: ignore + import pydantic.v1 - sys.modules["pydantic.fields"] = pydantic.v1.fields # type: ignore - sys.modules["pydantic.main"] = pydantic.v1.main # type: ignore - sys.modules["pydantic.errors"] = pydantic.v1.errors # type: ignore + sys.modules["pydantic.fields"] = pydantic.v1.fields # pyright: ignore [reportAttributeAccessIssue] + sys.modules["pydantic.main"] = pydantic.v1.main # pyright: ignore [reportAttributeAccessIssue] + sys.modules["pydantic.errors"] = pydantic.v1.errors # pyright: ignore [reportAttributeAccessIssue] sys.modules["pydantic"] = pydantic.v1 yield except (ImportError, AttributeError): diff --git a/reflex/utils/console.py b/reflex/utils/console.py index 900e5ed07c2..d5b7a0d6e14 100644 --- a/reflex/utils/console.py +++ b/reflex/utils/console.py @@ -196,7 +196,7 @@ def _get_first_non_framework_frame() -> FrameType | None: exclude_modules = [click, rx, typer, typing_extensions] exclude_roots = [ p.parent.resolve() - if (p := Path(m.__file__)).name == "__init__.py" + if (p := Path(m.__file__)).name == "__init__.py" # pyright: ignore [reportArgumentType] else p.resolve() for m in exclude_modules ] @@ -275,7 +275,7 @@ def ask( choices: list[str] | None = None, default: str | None = None, show_choices: bool = True, -) -> str: +) -> str | None: """Takes a prompt question and optionally a list of choices and returns the user input. @@ -290,7 +290,7 @@ def ask( """ return Prompt.ask( question, choices=choices, default=default, show_choices=show_choices - ) # type: ignore + ) def progress(): diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index 1e5cda10ba3..22322634d17 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -71,7 +71,7 @@ def notify_backend(): # run_process_and_launch_url is assumed to be used # only to launch the frontend # If this is not the case, might have to change the logic -def run_process_and_launch_url(run_command: list[str], backend_present=True): +def run_process_and_launch_url(run_command: list[str | None], backend_present=True): """Run the process and launch the URL. Args: @@ -89,7 +89,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True): if process is None: kwargs = {} if constants.IS_WINDOWS and backend_present: - kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore + kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue] process = processes.new_process( run_command, cwd=get_web_dir(), @@ -151,7 +151,7 @@ def run_frontend(root: Path, port: str, backend_present=True): console.rule("[bold green]App Running") os.environ["PORT"] = str(get_config().frontend_port if port is None else port) run_process_and_launch_url( - [prerequisites.get_package_manager(), "run", "dev"], # type: ignore + [prerequisites.get_package_manager(), "run", "dev"], backend_present, ) @@ -173,7 +173,7 @@ def run_frontend_prod(root: Path, port: str, backend_present=True): # Run the frontend in production mode. console.rule("[bold green]App Running") run_process_and_launch_url( - [prerequisites.get_package_manager(), "run", "prod"], # type: ignore + [prerequisites.get_package_manager(), "run", "prod"], backend_present, ) @@ -295,9 +295,11 @@ def run_granian_backend(host, port, loglevel: LogLevel): """ console.debug("Using Granian for backend") try: - from granian import Granian # type: ignore - from granian.constants import Interfaces # type: ignore - from granian.log import LogLevels # type: ignore + from granian import Granian # pyright: ignore [reportMissingImports] + from granian.constants import ( # pyright: ignore [reportMissingImports] + Interfaces, + ) + from granian.log import LogLevels # pyright: ignore [reportMissingImports] Granian( target=get_granian_target(), @@ -413,7 +415,9 @@ def run_granian_backend_prod(host, port, loglevel): from reflex.utils import processes try: - from granian.constants import Interfaces # type: ignore + from granian.constants import ( # pyright: ignore [reportMissingImports] + Interfaces, + ) command = [ "granian", @@ -482,7 +486,7 @@ def output_system_info(): dependencies.append(fnm_info) if system == "Linux": - import distro # type: ignore + import distro os_version = distro.name(pretty=True) else: @@ -494,11 +498,11 @@ def output_system_info(): console.debug(f"{dep}") console.debug( - f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" # type: ignore + f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" ) console.debug( f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}" - ) # type: ignore + ) if system != "Windows": console.debug(f"Unzip path: {path_ops.which('unzip')}") diff --git a/reflex/utils/format.py b/reflex/utils/format.py index 87d16055366..7973549b062 100644 --- a/reflex/utils/format.py +++ b/reflex/utils/format.py @@ -377,7 +377,7 @@ def format_prop( # For dictionaries, convert any properties to strings. elif isinstance(prop, dict): - prop = serializers.serialize_dict(prop) # type: ignore + prop = serializers.serialize_dict(prop) # pyright: ignore [reportAttributeAccessIssue] else: # Dump the prop as JSON. @@ -533,14 +533,14 @@ def format_queue_events( from reflex.vars import FunctionVar, Var if not events: - return Var("(() => null)").to(FunctionVar, EventChain) # type: ignore + return Var("(() => null)").to(FunctionVar, EventChain) # If no spec is provided, the function will take no arguments. def _default_args_spec(): return [] # Construct the arguments that the function accepts. - sig = inspect.signature(args_spec or _default_args_spec) # type: ignore + sig = inspect.signature(args_spec or _default_args_spec) if sig.parameters: arg_def = ",".join(f"_{p}" for p in sig.parameters) arg_def = f"({arg_def})" @@ -557,7 +557,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) # type: ignore + specs = call_event_fn(spec, args_spec or _default_args_spec) # pyright: ignore [reportAssignmentType, reportArgumentType] if isinstance(specs, Var): raise ValueError( f"Invalid event spec: {specs}. Expected a list of EventSpecs." @@ -569,7 +569,7 @@ def _default_args_spec(): return Var( f"{arg_def} => {{queueEvents([{','.join(payloads)}], {constants.CompileVars.SOCKET}); " f"processEvent({constants.CompileVars.SOCKET})}}", - ).to(FunctionVar, EventChain) # type: ignore + ).to(FunctionVar, EventChain) def format_query_params(router_data: dict[str, Any]) -> dict[str, str]: diff --git a/reflex/utils/imports.py b/reflex/utils/imports.py index ab217087c53..46e8e736239 100644 --- a/reflex/utils/imports.py +++ b/reflex/utils/imports.py @@ -122,7 +122,7 @@ def name(self) -> str: """ if self.alias: return ( - self.alias if self.is_default else " as ".join([self.tag, self.alias]) # type: ignore + self.alias if self.is_default else " as ".join([self.tag, self.alias]) # pyright: ignore [reportCallIssue,reportArgumentType] ) else: return self.tag or "" diff --git a/reflex/utils/prerequisites.py b/reflex/utils/prerequisites.py index 66c9156a9a3..edaa77aba63 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -176,7 +176,7 @@ def get_node_version() -> version.Version | None: try: result = processes.new_process([node_path, "-v"], run=True) # The output will be in the form "vX.Y.Z", but version.parse() can handle it - return version.parse(result.stdout) # type: ignore + return version.parse(result.stdout) # pyright: ignore [reportArgumentType] except (FileNotFoundError, TypeError): return None @@ -189,7 +189,7 @@ def get_fnm_version() -> version.Version | None: """ try: result = processes.new_process([constants.Fnm.EXE, "--version"], run=True) - return version.parse(result.stdout.split(" ")[1]) # type: ignore + return version.parse(result.stdout.split(" ")[1]) # pyright: ignore [reportOptionalMemberAccess, reportAttributeAccessIssue] except (FileNotFoundError, TypeError): return None except version.InvalidVersion as e: @@ -211,7 +211,7 @@ def get_bun_version() -> version.Version | None: try: # Run the bun -v command and capture the output result = processes.new_process([str(bun_path), "-v"], run=True) - return version.parse(str(result.stdout)) + return version.parse(str(result.stdout)) # pyright: ignore [reportArgumentType] except FileNotFoundError: return None except version.InvalidVersion as e: @@ -1188,7 +1188,7 @@ def install_frontend_packages(packages: set[str], config: Config): ) processes.run_process_with_fallback( - [install_package_manager, "install"], # type: ignore + [install_package_manager, "install"], fallback=fallback_command, analytics_enabled=True, show_status_message="Installing base frontend packages", @@ -1481,7 +1481,7 @@ def format_demo_url_str(url: str) -> str: ) # Return the template. - return templates[int(template)].name + return templates[int(template)].name # pyright: ignore [reportArgumentType] def fetch_app_templates(version: str) -> dict[str, Template]: diff --git a/reflex/utils/processes.py b/reflex/utils/processes.py index 575688eda39..94e0fda3ec6 100644 --- a/reflex/utils/processes.py +++ b/reflex/utils/processes.py @@ -62,7 +62,7 @@ def get_process_on_port(port) -> Optional[psutil.Process]: psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess ): if importlib.metadata.version("psutil") >= "6.0.0": - conns = proc.net_connections(kind="inet") # type: ignore + conns = proc.net_connections(kind="inet") else: conns = proc.connections(kind="inet") for conn in conns: @@ -91,7 +91,7 @@ def kill_process_on_port(port): """ if get_process_on_port(port) is not None: with contextlib.suppress(psutil.AccessDenied): - get_process_on_port(port).kill() # type: ignore + get_process_on_port(port).kill() # pyright: ignore [reportOptionalMemberAccess] def change_port(port: str, _type: str) -> str: @@ -212,14 +212,14 @@ def run_concurrently_context( return # Convert the functions to tuples. - fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # type: ignore + fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # pyright: ignore [reportAssignmentType] # Run the functions concurrently. executor = None try: executor = futures.ThreadPoolExecutor(max_workers=len(fns)) # Submit the tasks. - tasks = [executor.submit(*fn) for fn in fns] # type: ignore + tasks = [executor.submit(*fn) for fn in fns] # pyright: ignore [reportArgumentType] # 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 152c0694996..5a8cad18e3e 100644 --- a/reflex/utils/pyi_generator.py +++ b/reflex/utils/pyi_generator.py @@ -229,7 +229,7 @@ def _generate_imports( """ return [ *[ - ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) + ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) # pyright: ignore [reportCallIssue] for name, values in DEFAULT_IMPORTS.items() ], ast.Import([ast.alias("reflex")]), @@ -367,7 +367,7 @@ def _extract_class_props_as_ast_nodes( # Try to get default from pydantic field definition. default = target_class.__fields__[name].default if isinstance(default, Var): - default = default._decode() # type: ignore + default = default._decode() kwargs.append( ( @@ -434,10 +434,12 @@ def type_to_ast(typ, cls: type) -> ast.AST: if len(arg_nodes) == 1: slice_value = arg_nodes[0] else: - slice_value = ast.Tuple(elts=arg_nodes, ctx=ast.Load()) + slice_value = ast.Tuple(elts=arg_nodes, ctx=ast.Load()) # pyright: ignore [reportArgumentType] return ast.Subscript( - value=ast.Name(id=base_name), slice=ast.Index(value=slice_value), ctx=ast.Load() + value=ast.Name(id=base_name), + slice=ast.Index(value=slice_value), # pyright: ignore [reportArgumentType] + ctx=ast.Load(), ) @@ -575,7 +577,7 @@ def figure_out_return_type(annotation: Any): arg=trigger, annotation=ast.Subscript( ast.Name("Optional"), - ast.Index( # type: ignore + ast.Index( # pyright: ignore [reportArgumentType] value=ast.Name( id=ast.unparse( figure_out_return_type( @@ -621,7 +623,7 @@ def figure_out_return_type(annotation: Any): definition = ast.FunctionDef( name="create", args=create_args, - body=[ + body=[ # pyright: ignore [reportArgumentType] ast.Expr( value=ast.Constant( value=_generate_docstrings( @@ -630,7 +632,7 @@ def figure_out_return_type(annotation: Any): ), ), ast.Expr( - value=ast.Ellipsis(), + value=ast.Constant(value=Ellipsis), ), ], decorator_list=[ @@ -641,7 +643,7 @@ def figure_out_return_type(annotation: Any): else [ast.Name(id="classmethod")] ), ], - lineno=node.lineno if node is not None else None, + lineno=node.lineno if node is not None else None, # pyright: ignore [reportArgumentType] returns=ast.Constant(value=clz.__name__), ) return definition @@ -690,7 +692,7 @@ def _generate_staticmethod_call_functiondef( ), ], decorator_list=[ast.Name(id="staticmethod")], - lineno=node.lineno if node is not None else None, + lineno=node.lineno if node is not None else None, # pyright: ignore [reportArgumentType] returns=ast.Constant( value=_get_type_hint( typing.get_type_hints(clz.__call__).get("return", None), @@ -726,17 +728,17 @@ def _generate_namespace_call_functiondef( clz = classes[clz_name] if not hasattr(clz.__call__, "__self__"): - return _generate_staticmethod_call_functiondef(node, clz, type_hint_globals) # type: ignore + return _generate_staticmethod_call_functiondef(node, clz, type_hint_globals) # pyright: ignore [reportArgumentType] # Determine which class is wrapped by the namespace __call__ method component_clz = clz.__call__.__self__ - if clz.__call__.__func__.__name__ != "create": + if clz.__call__.__func__.__name__ != "create": # pyright: ignore [reportFunctionMemberAccess] return None definition = _generate_component_create_functiondef( node=None, - clz=component_clz, # type: ignore + clz=component_clz, # pyright: ignore [reportArgumentType] type_hint_globals=type_hint_globals, ) definition.name = "__call__" @@ -816,7 +818,7 @@ def visit_Module(self, node: ast.Module) -> ast.Module: The modified Module node. """ self.generic_visit(node) - return self._remove_docstring(node) # type: ignore + return self._remove_docstring(node) # pyright: ignore [reportReturnType] def visit_Import( self, node: ast.Import | ast.ImportFrom @@ -914,7 +916,7 @@ def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef: node.body.append(call_definition) if not node.body: # We should never return an empty body. - node.body.append(ast.Expr(value=ast.Ellipsis())) + node.body.append(ast.Expr(value=ast.Constant(value=Ellipsis))) self.current_class = None return node @@ -941,9 +943,9 @@ def visit_FunctionDef(self, node: ast.FunctionDef) -> Any: if node.name.startswith("_") and node.name != "__call__": return None # remove private methods - if node.body[-1] != ast.Expr(value=ast.Ellipsis()): + if node.body[-1] != ast.Expr(value=ast.Constant(value=Ellipsis)): # Blank out the function body for public functions. - node.body = [ast.Expr(value=ast.Ellipsis())] + node.body = [ast.Expr(value=ast.Constant(value=Ellipsis))] return node def visit_Assign(self, node: ast.Assign) -> ast.Assign | None: @@ -1077,7 +1079,7 @@ def _get_init_lazy_imports(self, mod, new_tree): + ( " # type: ignore" if mod in pyright_ignore_imports - else " # noqa" # ignore ruff formatting here for cases like rx.list. + else " # noqa: F401" # ignore ruff formatting here for cases like rx.list. if isinstance(mod, tuple) else "" ) diff --git a/reflex/utils/serializers.py b/reflex/utils/serializers.py index 4bb8dea9243..f78438522bc 100644 --- a/reflex/utils/serializers.py +++ b/reflex/utils/serializers.py @@ -476,7 +476,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() # type: ignore + mime_type = image.get_format_mimetype() # pyright: ignore [reportAttributeAccessIssue] except AttributeError: try: # Fallback method diff --git a/reflex/utils/types.py b/reflex/utils/types.py index 0b3ec7e9f37..6257b14721b 100644 --- a/reflex/utils/types.py +++ b/reflex/utils/types.py @@ -24,7 +24,7 @@ Tuple, Type, Union, - _GenericAlias, # type: ignore + _GenericAlias, # pyright: ignore [reportAttributeAccessIssue] get_args, get_type_hints, ) @@ -39,7 +39,9 @@ try: from pydantic.v1.fields import ModelField except ModuleNotFoundError: - from pydantic.fields import ModelField # type: ignore + from pydantic.fields import ( + ModelField, # pyright: ignore [reportAttributeAccessIssue] + ) from sqlalchemy.ext.associationproxy import AssociationProxyInstance from sqlalchemy.ext.hybrid import hybrid_property @@ -70,13 +72,15 @@ def override(func: Callable) -> Callable: with contextlib.suppress(ImportError): # For newer versions of Python. - from types import GenericAlias # type: ignore + from types import GenericAlias GenericAliasTypes.append(GenericAlias) with contextlib.suppress(ImportError): # For older versions of Python. - from typing import _SpecialGenericAlias # type: ignore + from typing import ( + _SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue] + ) GenericAliasTypes.append(_SpecialGenericAlias) @@ -175,7 +179,7 @@ def is_generic_alias(cls: GenericType) -> bool: Returns: Whether the class is a generic alias. """ - return isinstance(cls, GenericAliasTypes) + return isinstance(cls, GenericAliasTypes) # pyright: ignore [reportArgumentType] def unionize(*args: GenericType) -> Type: @@ -188,14 +192,14 @@ def unionize(*args: GenericType) -> Type: The unionized types. """ if not args: - return Any + return Any # pyright: ignore [reportReturnType] if len(args) == 1: return args[0] # We are bisecting the args list here to avoid hitting the recursion limit # In Python versions >= 3.11, we can simply do `return Union[*args]` midpoint = len(args) // 2 first_half, second_half = args[:midpoint], args[midpoint:] - return Union[unionize(*first_half), unionize(*second_half)] + return Union[unionize(*first_half), unionize(*second_half)] # pyright: ignore [reportReturnType] def is_none(cls: GenericType) -> bool: @@ -351,13 +355,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 # type: ignore + item_type = column_type.item_type.python_type # pyright: ignore [reportAttributeAccessIssue] except NotImplementedError: item_type = None if item_type is not None: if type_ in PrimitiveToAnnotation: - type_ = PrimitiveToAnnotation[type_] # type: ignore - type_ = type_[item_type] # type: ignore + type_ = PrimitiveToAnnotation[type_] + type_ = type_[item_type] # pyright: ignore [reportIndexIssue] if column.nullable: type_ = Optional[type_] return type_ @@ -432,7 +436,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)) + return tuple(get_base_class(arg) for arg in get_args(cls)) # pyright: ignore [reportReturnType] return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls diff --git a/reflex/vars/base.py b/reflex/vars/base.py index a3b3059e90c..ac48355c4e1 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -662,7 +662,7 @@ def to( return self.to(var_subclass.var_subclass, output) if fixed_output_type is None: - return get_to_operation(NoneVar).create(self) # type: ignore + return get_to_operation(NoneVar).create(self) # pyright: ignore [reportReturnType] # Handle fixed_output_type being Base or a dataclass. if can_use_in_object_var(fixed_output_type): @@ -679,7 +679,7 @@ def to( to_operation_return = var_subclass.to_var_subclass.create( value=self, _var_type=new_var_type ) - return to_operation_return # type: ignore + return to_operation_return # pyright: ignore [reportReturnType] # If we can't determine the first argument, we just replace the _var_type. if not issubclass(output, Var) or var_type is None: @@ -1095,7 +1095,7 @@ def _decode(self) -> Any: The decoded value or the Var name. """ if isinstance(self, LiteralVar): - return self._var_value # type: ignore + return self._var_value try: return json.loads(str(self)) except ValueError: @@ -1222,7 +1222,7 @@ def _get_all_var_data(self) -> VarData | None: """ return VarData.merge( self._original._get_all_var_data(), - self._var_data, # type: ignore + self._var_data, ) @classmethod @@ -1243,10 +1243,10 @@ def create( The ToOperation. """ return cls( - _js_expr="", # type: ignore - _var_data=_var_data, # type: ignore - _var_type=_var_type or cls._default_var_type, # type: ignore - _original=value, # type: ignore + _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] ) @@ -1435,7 +1435,7 @@ def get_python_literal(value: Union[LiteralVar, Any]) -> Any | None: # NoReturn is used to match CustomVarOperationReturn with no type hint. @overload -def var_operation( +def var_operation( # pyright: ignore [reportOverlappingOverload] func: Callable[P, CustomVarOperationReturn[NoReturn]], ) -> Callable[P, Var]: ... @@ -1485,7 +1485,7 @@ def var_operation( ) -> Callable[P, Var[T]]: ... -def var_operation( +def var_operation( # pyright: ignore [reportInconsistentOverload] func: Callable[P, CustomVarOperationReturn[T]], ) -> Callable[P, Var[T]]: """Decorator for creating a var operation. @@ -1519,7 +1519,7 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]: return CustomVarOperation.create( name=func.__name__, args=tuple(list(args_vars.items()) + list(kwargs_vars.items())), - return_var=func(*args_vars.values(), **kwargs_vars), # type: ignore + return_var=func(*args_vars.values(), **kwargs_vars), # pyright: ignore [reportCallIssue, reportReturnType] ).guess_type() return wrapper @@ -1589,7 +1589,7 @@ def __getattr__(self, name: str) -> Any: next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1] - return next_class.__getattr__(self, name) # type: ignore + return next_class.__getattr__(self, name) def _get_all_var_data(self) -> VarData | None: """Get all VarData associated with the Var. @@ -1611,7 +1611,7 @@ def _cached_get_all_var_data(self) -> VarData | None: value._get_all_var_data() if isinstance(value, Var) else None for value in ( getattr(self, field.name) - for field in dataclasses.fields(self) # type: ignore + for field in dataclasses.fields(self) # pyright: ignore [reportArgumentType] ) ), self._var_data, @@ -1628,7 +1628,7 @@ def __hash__(self) -> int: type(self).__name__, *[ getattr(self, field.name) - for field in dataclasses.fields(self) # type: ignore + for field in dataclasses.fields(self) # pyright: ignore [reportArgumentType] if field.name not in ["_js_expr", "_var_data", "_var_type"] ], ) @@ -1645,7 +1645,7 @@ def and_operation(a: Var | Any, b: Var | Any) -> Var: Returns: The result of the logical AND operation. """ - return _and_operation(a, b) # type: ignore + return _and_operation(a, b) @var_operation @@ -1675,7 +1675,7 @@ def or_operation(a: Var | Any, b: Var | Any) -> Var: Returns: The result of the logical OR operation. """ - return _or_operation(a, b) # type: ignore + return _or_operation(a, b) @var_operation @@ -1804,7 +1804,7 @@ class ComputedVar(Var[RETURN_TYPE]): _fget: Callable[[BaseState], RETURN_TYPE] = dataclasses.field( default_factory=lambda: lambda _: None - ) # type: ignore + ) # pyright: ignore [reportAssignmentType] def __init__( self, @@ -2088,10 +2088,10 @@ def _deps( return set() with contextlib.suppress(AttributeError): # unbox functools.partial - obj = cast(FunctionType, obj.func) # type: ignore + obj = cast(FunctionType, obj.func) # pyright: ignore [reportAttributeAccessIssue] with contextlib.suppress(AttributeError): # unbox EventHandler - obj = cast(FunctionType, obj.fn) # type: ignore + obj = cast(FunctionType, obj.fn) # pyright: ignore [reportAttributeAccessIssue] if self_name is None and isinstance(obj, FunctionType): try: @@ -2131,7 +2131,7 @@ def _deps( d.update( self._deps( objclass=objclass, - obj=ref_obj, + obj=ref_obj, # pyright: ignore [reportArgumentType] ) ) # recurse into property fget functions @@ -2141,7 +2141,7 @@ def _deps( d.update( self._deps( objclass=objclass, - obj=ref_obj.fget, # type: ignore + obj=ref_obj.fget, # pyright: ignore [reportArgumentType] ) ) elif ( @@ -2183,7 +2183,7 @@ def _determine_var_type(self) -> Type: hints = get_type_hints(self._fget) if "return" in hints: return hints["return"] - return Any + return Any # pyright: ignore [reportReturnType] @property def __class__(self) -> Type: @@ -2224,7 +2224,7 @@ def computed_var( interval: Optional[Union[datetime.timedelta, int]] = None, backend: bool | None = None, **kwargs, -) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ... +) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ... # pyright: ignore [reportInvalidTypeVarUse] @overload @@ -2553,7 +2553,7 @@ def get_uuid_string_var() -> Var: unique_uuid_var = get_unique_variable_name() unique_uuid_var_data = VarData( imports={ - f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore + f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # pyright: ignore [reportArgumentType] "react": "useMemo", }, hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None}, @@ -2613,7 +2613,7 @@ def _extract_var_data(value: Iterable) -> list[VarData | None]: elif not isinstance(sub, str): # Recurse into dict values. if hasattr(sub, "values") and callable(sub.values): - var_datas.extend(_extract_var_data(sub.values())) + var_datas.extend(_extract_var_data(sub.values())) # pyright: ignore [reportArgumentType] # Recurse into iterable values (or dict keys). var_datas.extend(_extract_var_data(sub)) @@ -2624,7 +2624,7 @@ def _extract_var_data(value: Iterable) -> list[VarData | None]: # Recurse when value is a dict itself. values = getattr(value, "values", None) if callable(values): - var_datas.extend(_extract_var_data(values())) + var_datas.extend(_extract_var_data(values())) # pyright: ignore [reportArgumentType] return var_datas @@ -2932,7 +2932,7 @@ def __get__(self, instance: None, owner) -> Var[FIELD_TYPE]: ... @overload def __get__(self, instance, owner) -> FIELD_TYPE: ... - def __get__(self, instance, owner): # type: ignore + def __get__(self, instance, owner): # pyright: ignore [reportInconsistentOverload] """Get the Var. Args: @@ -2950,4 +2950,4 @@ def field(value: FIELD_TYPE) -> Field[FIELD_TYPE]: Returns: The Field. """ - return value # type: ignore + return value # pyright: ignore [reportReturnType] diff --git a/reflex/vars/datetime.py b/reflex/vars/datetime.py index b6f4c24c615..b20cfc7a6ce 100644 --- a/reflex/vars/datetime.py +++ b/reflex/vars/datetime.py @@ -40,7 +40,7 @@ class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)): def __lt__(self, other: datetime_types) -> BooleanVar: ... @overload - def __lt__(self, other: NoReturn) -> NoReturn: ... + def __lt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __lt__(self, other: Any): """Less than comparison. @@ -59,7 +59,7 @@ def __lt__(self, other: Any): def __le__(self, other: datetime_types) -> BooleanVar: ... @overload - def __le__(self, other: NoReturn) -> NoReturn: ... + def __le__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __le__(self, other: Any): """Less than or equal comparison. @@ -78,7 +78,7 @@ def __le__(self, other: Any): def __gt__(self, other: datetime_types) -> BooleanVar: ... @overload - def __gt__(self, other: NoReturn) -> NoReturn: ... + def __gt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __gt__(self, other: Any): """Greater than comparison. @@ -97,7 +97,7 @@ def __gt__(self, other: Any): def __ge__(self, other: datetime_types) -> BooleanVar: ... @overload - def __ge__(self, other: NoReturn) -> NoReturn: ... + def __ge__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __ge__(self, other: Any): """Greater than or equal comparison. diff --git a/reflex/vars/function.py b/reflex/vars/function.py index 131f15b9f48..a82c4964b7b 100644 --- a/reflex/vars/function.py +++ b/reflex/vars/function.py @@ -100,7 +100,7 @@ def partial( @overload def partial(self, *args: Var | Any) -> FunctionVar: ... - def partial(self, *args: Var | Any) -> FunctionVar: # type: ignore + def partial(self, *args: Var | Any) -> FunctionVar: # pyright: ignore [reportInconsistentOverload] """Partially apply the function with the given arguments. Args: @@ -174,7 +174,7 @@ def call( @overload def call(self, *args: Var | Any) -> Var: ... - def call(self, *args: Var | Any) -> Var: # type: ignore + def call(self, *args: Var | Any) -> Var: # pyright: ignore [reportInconsistentOverload] """Call the function with the given arguments. Args: diff --git a/reflex/vars/number.py b/reflex/vars/number.py index 08233445096..475c08b5538 100644 --- a/reflex/vars/number.py +++ b/reflex/vars/number.py @@ -61,7 +61,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): def __add__(self, other: number_types) -> NumberVar: ... @overload - def __add__(self, other: NoReturn) -> NoReturn: ... + def __add__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __add__(self, other: Any): """Add two numbers. @@ -80,7 +80,7 @@ def __add__(self, other: Any): def __radd__(self, other: number_types) -> NumberVar: ... @overload - def __radd__(self, other: NoReturn) -> NoReturn: ... + def __radd__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __radd__(self, other: Any): """Add two numbers. @@ -99,7 +99,7 @@ def __radd__(self, other: Any): def __sub__(self, other: number_types) -> NumberVar: ... @overload - def __sub__(self, other: NoReturn) -> NoReturn: ... + def __sub__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __sub__(self, other: Any): """Subtract two numbers. @@ -119,7 +119,7 @@ def __sub__(self, other: Any): def __rsub__(self, other: number_types) -> NumberVar: ... @overload - def __rsub__(self, other: NoReturn) -> NoReturn: ... + def __rsub__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rsub__(self, other: Any): """Subtract two numbers. @@ -201,7 +201,7 @@ def __rmul__(self, other: Any): def __truediv__(self, other: number_types) -> NumberVar: ... @overload - def __truediv__(self, other: NoReturn) -> NoReturn: ... + def __truediv__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __truediv__(self, other: Any): """Divide two numbers. @@ -221,7 +221,7 @@ def __truediv__(self, other: Any): def __rtruediv__(self, other: number_types) -> NumberVar: ... @overload - def __rtruediv__(self, other: NoReturn) -> NoReturn: ... + def __rtruediv__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rtruediv__(self, other: Any): """Divide two numbers. @@ -241,7 +241,7 @@ def __rtruediv__(self, other: Any): def __floordiv__(self, other: number_types) -> NumberVar: ... @overload - def __floordiv__(self, other: NoReturn) -> NoReturn: ... + def __floordiv__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __floordiv__(self, other: Any): """Floor divide two numbers. @@ -261,7 +261,7 @@ def __floordiv__(self, other: Any): def __rfloordiv__(self, other: number_types) -> NumberVar: ... @overload - def __rfloordiv__(self, other: NoReturn) -> NoReturn: ... + def __rfloordiv__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rfloordiv__(self, other: Any): """Floor divide two numbers. @@ -281,7 +281,7 @@ def __rfloordiv__(self, other: Any): def __mod__(self, other: number_types) -> NumberVar: ... @overload - def __mod__(self, other: NoReturn) -> NoReturn: ... + def __mod__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __mod__(self, other: Any): """Modulo two numbers. @@ -301,7 +301,7 @@ def __mod__(self, other: Any): def __rmod__(self, other: number_types) -> NumberVar: ... @overload - def __rmod__(self, other: NoReturn) -> NoReturn: ... + def __rmod__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rmod__(self, other: Any): """Modulo two numbers. @@ -321,7 +321,7 @@ def __rmod__(self, other: Any): def __pow__(self, other: number_types) -> NumberVar: ... @overload - def __pow__(self, other: NoReturn) -> NoReturn: ... + def __pow__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __pow__(self, other: Any): """Exponentiate two numbers. @@ -341,7 +341,7 @@ def __pow__(self, other: Any): def __rpow__(self, other: number_types) -> NumberVar: ... @overload - def __rpow__(self, other: NoReturn) -> NoReturn: ... + def __rpow__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rpow__(self, other: Any): """Exponentiate two numbers. @@ -417,7 +417,7 @@ def __trunc__(self): def __lt__(self, other: number_types) -> BooleanVar: ... @overload - def __lt__(self, other: NoReturn) -> NoReturn: ... + def __lt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __lt__(self, other: Any): """Less than comparison. @@ -436,7 +436,7 @@ def __lt__(self, other: Any): def __le__(self, other: number_types) -> BooleanVar: ... @overload - def __le__(self, other: NoReturn) -> NoReturn: ... + def __le__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __le__(self, other: Any): """Less than or equal comparison. @@ -481,7 +481,7 @@ def __ne__(self, other: Any): def __gt__(self, other: number_types) -> BooleanVar: ... @overload - def __gt__(self, other: NoReturn) -> NoReturn: ... + def __gt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __gt__(self, other: Any): """Greater than comparison. @@ -500,7 +500,7 @@ def __gt__(self, other: Any): def __ge__(self, other: number_types) -> BooleanVar: ... @overload - def __ge__(self, other: NoReturn) -> NoReturn: ... + def __ge__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __ge__(self, other: Any): """Greater than or equal comparison. @@ -561,7 +561,7 @@ def wrapper(lhs: number_types, rhs: number_types) -> NumberVar: Returns: The binary number operation. """ - return operation(lhs, rhs) # type: ignore + return operation(lhs, rhs) # pyright: ignore [reportReturnType, reportArgumentType] return wrapper diff --git a/reflex/vars/object.py b/reflex/vars/object.py index 7b951c559c8..fa8cdf8ec56 100644 --- a/reflex/vars/object.py +++ b/reflex/vars/object.py @@ -75,9 +75,9 @@ def _value_type(self) -> Type: """ fixed_type = get_origin(self._var_type) or self._var_type if not isclass(fixed_type): - return Any + return Any # pyright: ignore [reportReturnType] args = get_args(self._var_type) if issubclass(fixed_type, Mapping) else () - return args[1] if args else Any + return args[1] if args else Any # pyright: ignore [reportReturnType] def keys(self) -> ArrayVar[List[str]]: """Get the keys of the object. @@ -134,7 +134,7 @@ def merge(self, other: ObjectVar): # NoReturn is used here to catch when key value is Any @overload - def __getitem__( + def __getitem__( # pyright: ignore [reportOverlappingOverload] self: ObjectVar[Mapping[Any, NoReturn]], key: Var | Any, ) -> Var: ... @@ -202,7 +202,7 @@ def __getitem__(self, key: Var | Any) -> Var: # NoReturn is used here to catch when key value is Any @overload - def __getattr__( + def __getattr__( # pyright: ignore [reportOverlappingOverload] self: ObjectVar[Mapping[Any, NoReturn]], name: str, ) -> Var: ... @@ -321,7 +321,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 + return args_list[0] if args_list else Any # pyright: ignore [reportReturnType] def _value_type(self) -> Type: """Get the type of the values of the object. @@ -330,7 +330,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 + return args_list[1] if args_list else Any # pyright: ignore [reportReturnType] @cached_property_no_lock def _cached_var_name(self) -> str: diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py index 1b11f50e6e1..fa1ab5bf3f8 100644 --- a/reflex/vars/sequence.py +++ b/reflex/vars/sequence.py @@ -66,7 +66,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): def __add__(self, other: StringVar | str) -> ConcatVarOperation: ... @overload - def __add__(self, other: NoReturn) -> NoReturn: ... + def __add__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __add__(self, other: Any) -> ConcatVarOperation: """Concatenate two strings. @@ -86,7 +86,7 @@ def __add__(self, other: Any) -> ConcatVarOperation: def __radd__(self, other: StringVar | str) -> ConcatVarOperation: ... @overload - def __radd__(self, other: NoReturn) -> NoReturn: ... + def __radd__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __radd__(self, other: Any) -> ConcatVarOperation: """Concatenate two strings. @@ -106,7 +106,7 @@ def __radd__(self, other: Any) -> ConcatVarOperation: def __mul__(self, other: NumberVar | int) -> StringVar: ... @overload - def __mul__(self, other: NoReturn) -> NoReturn: ... + def __mul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __mul__(self, other: Any) -> StringVar: """Multiply the sequence by a number or an integer. @@ -126,7 +126,7 @@ def __mul__(self, other: Any) -> StringVar: def __rmul__(self, other: NumberVar | int) -> StringVar: ... @overload - def __rmul__(self, other: NoReturn) -> NoReturn: ... + def __rmul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __rmul__(self, other: Any) -> StringVar: """Multiply the sequence by a number or an integer. @@ -211,7 +211,7 @@ def contains( ) -> BooleanVar: ... @overload - def contains( + def contains( # pyright: ignore [reportOverlappingOverload] self, other: NoReturn, field: StringVar | str | None = None ) -> NoReturn: ... @@ -237,7 +237,7 @@ def contains(self, other: Any, field: Any = None) -> BooleanVar: def split(self, separator: StringVar | str = "") -> ArrayVar[List[str]]: ... @overload - def split(self, separator: NoReturn) -> NoReturn: ... + def split(self, separator: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def split(self, separator: Any = "") -> ArrayVar[List[str]]: """Split the string. @@ -256,7 +256,7 @@ def split(self, separator: Any = "") -> ArrayVar[List[str]]: def startswith(self, prefix: StringVar | str) -> BooleanVar: ... @overload - def startswith(self, prefix: NoReturn) -> NoReturn: ... + def startswith(self, prefix: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def startswith(self, prefix: Any) -> BooleanVar: """Check if the string starts with a prefix. @@ -275,7 +275,7 @@ def startswith(self, prefix: Any) -> BooleanVar: def endswith(self, suffix: StringVar | str) -> BooleanVar: ... @overload - def endswith(self, suffix: NoReturn) -> NoReturn: ... + def endswith(self, suffix: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def endswith(self, suffix: Any) -> BooleanVar: """Check if the string ends with a suffix. @@ -294,7 +294,7 @@ def endswith(self, suffix: Any) -> BooleanVar: def __lt__(self, other: StringVar | str) -> BooleanVar: ... @overload - def __lt__(self, other: NoReturn) -> NoReturn: ... + def __lt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __lt__(self, other: Any): """Check if the string is less than another string. @@ -314,7 +314,7 @@ def __lt__(self, other: Any): def __gt__(self, other: StringVar | str) -> BooleanVar: ... @overload - def __gt__(self, other: NoReturn) -> NoReturn: ... + def __gt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __gt__(self, other: Any): """Check if the string is greater than another string. @@ -334,7 +334,7 @@ def __gt__(self, other: Any): def __le__(self, other: StringVar | str) -> BooleanVar: ... @overload - def __le__(self, other: NoReturn) -> NoReturn: ... + def __le__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __le__(self, other: Any): """Check if the string is less than or equal to another string. @@ -354,7 +354,7 @@ def __le__(self, other: Any): def __ge__(self, other: StringVar | str) -> BooleanVar: ... @overload - def __ge__(self, other: NoReturn) -> NoReturn: ... + def __ge__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __ge__(self, other: Any): """Check if the string is greater than or equal to another string. @@ -811,7 +811,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): def join(self, sep: StringVar | str = "") -> StringVar: ... @overload - def join(self, sep: NoReturn) -> NoReturn: ... + def join(self, sep: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def join(self, sep: Any = "") -> StringVar: """Join the elements of the array. @@ -858,7 +858,7 @@ def reverse(self) -> ArrayVar[ARRAY_VAR_TYPE]: def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: ... @overload - def __add__(self, other: NoReturn) -> NoReturn: ... + def __add__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __add__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]: """Concatenate two arrays. @@ -1089,7 +1089,7 @@ def pluck(self, field: StringVar | str) -> ArrayVar: def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: ... @overload - def __mul__(self, other: NoReturn) -> NoReturn: ... + def __mul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload] def __mul__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]: """Multiply the sequence by a number or integer. @@ -1107,7 +1107,7 @@ def __mul__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]: return repeat_array_operation(self, other) - __rmul__ = __mul__ # type: ignore + __rmul__ = __mul__ @overload def __lt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ... @@ -1691,7 +1691,7 @@ def array_concat_operation( """ return var_operation_return( js_expression=f"[...{lhs}, ...{rhs}]", - var_type=Union[lhs._var_type, rhs._var_type], + var_type=Union[lhs._var_type, rhs._var_type], # pyright: ignore [reportArgumentType] ) diff --git a/tests/integration/test_background_task.py b/tests/integration/test_background_task.py index cb8fda019ce..f312f81221f 100644 --- a/tests/integration/test_background_task.py +++ b/tests/integration/test_background_task.py @@ -37,9 +37,9 @@ async def handle_event_yield_only(self): self._task_id += 1 for ix in range(int(self.iterations)): if ix % 2 == 0: - yield State.increment_arbitrary(1) # type: ignore + yield State.increment_arbitrary(1) else: - yield State.increment() # type: ignore + yield State.increment() await asyncio.sleep(0.005) @rx.event @@ -125,8 +125,8 @@ def index() -> rx.Component: rx.input( id="iterations", placeholder="Iterations", - value=State.iterations.to_string(), # type: ignore - on_change=State.set_iterations, # type: ignore + value=State.iterations.to_string(), # pyright: ignore [reportAttributeAccessIssue] + on_change=State.set_iterations, # pyright: ignore [reportAttributeAccessIssue] ), rx.button( "Delayed Increment", @@ -288,7 +288,7 @@ def test_background_task( assert background_task._poll_for(lambda: counter.text == "620", timeout=40) # all tasks should have exited and cleaned up assert background_task._poll_for( - lambda: not background_task.app_instance._background_tasks # type: ignore + lambda: not background_task.app_instance._background_tasks # pyright: ignore [reportOptionalMemberAccess] ) diff --git a/tests/integration/test_component_state.py b/tests/integration/test_component_state.py index 381c1d23a37..654dc7ce9de 100644 --- a/tests/integration/test_component_state.py +++ b/tests/integration/test_component_state.py @@ -30,7 +30,7 @@ class MultiCounter(rx.ComponentState, Generic[E]): @rx.event def increment(self): self.count += 1 - self._be = self.count # type: ignore + self._be = self.count # pyright: ignore [reportAttributeAccessIssue] @classmethod def get_component(cls, *children, **props): @@ -72,7 +72,7 @@ def increment(self): State=_Counter, ) - app = rx.App(_state=rx.State) # noqa + app = rx.App(_state=rx.State) # noqa: F841 @rx.page() def index(): @@ -89,7 +89,7 @@ def index(): mc_d, rx.button( "Inc A", - on_click=mc_a.State.increment, # type: ignore + on_click=mc_a.State.increment, # pyright: ignore [reportAttributeAccessIssue, reportOptionalMemberAccess] id="inc-a", ), rx.text( diff --git a/tests/integration/test_connection_banner.py b/tests/integration/test_connection_banner.py index c2a912af635..c80f30626f7 100644 --- a/tests/integration/test_connection_banner.py +++ b/tests/integration/test_connection_banner.py @@ -31,7 +31,7 @@ def index(): rx.button( "Increment", id="increment", - on_click=State.set_foo(State.foo + 1), # type: ignore + on_click=State.set_foo(State.foo + 1), # pyright: ignore [reportAttributeAccessIssue] ), rx.button("Delay", id="delay", on_click=State.delay), ) diff --git a/tests/integration/test_deploy_url.py b/tests/integration/test_deploy_url.py index 8b577626024..207f3760984 100644 --- a/tests/integration/test_deploy_url.py +++ b/tests/integration/test_deploy_url.py @@ -19,7 +19,7 @@ def DeployUrlSample() -> None: class State(rx.State): @rx.event def goto_self(self): - return rx.redirect(rx.config.get_config().deploy_url) # type: ignore + return rx.redirect(rx.config.get_config().deploy_url) # pyright: ignore [reportArgumentType] def index(): return rx.fragment( diff --git a/tests/integration/test_dynamic_routes.py b/tests/integration/test_dynamic_routes.py index 9032fd84c46..40886a601c1 100644 --- a/tests/integration/test_dynamic_routes.py +++ b/tests/integration/test_dynamic_routes.py @@ -49,7 +49,7 @@ def index(): read_only=True, id="token", ), - rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # type: ignore + rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # pyright: ignore [reportAttributeAccessIssue] rx.input( value=DynamicState.router.page.raw_path, read_only=True, @@ -60,12 +60,12 @@ def index(): rx.link( "next", href="/page/" + DynamicState.next_page, - id="link_page_next", # type: ignore + id="link_page_next", ), rx.link("missing", href="/missing", id="link_missing"), - rx.list( # type: ignore + rx.list( # pyright: ignore [reportAttributeAccessIssue] rx.foreach( - DynamicState.order, # type: ignore + DynamicState.order, # pyright: ignore [reportAttributeAccessIssue] lambda i: rx.list_item(rx.text(i)), ), ), @@ -98,11 +98,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"), # type: ignore + rx.data_list.value(rx.State.arg_str, id="state-arg_str"), # pyright: ignore [reportAttributeAccessIssue] ), rx.data_list.item( rx.data_list.label("ArgState.arg_str (dynamic) (inherited)"), - rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # type: ignore + rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # pyright: ignore [reportAttributeAccessIssue] ), rx.data_list.item( rx.data_list.label("ArgState.arg"), @@ -110,7 +110,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"), # type: ignore + rx.data_list.value(ArgSubState.arg_str, id="argsubstate-arg_str"), # pyright: ignore [reportAttributeAccessIssue] ), rx.data_list.item( rx.data_list.label("ArgSubState.arg (inherited)"), @@ -134,15 +134,15 @@ def arg() -> rx.Component: height="100vh", ) - @rx.page(route="/redirect-page/[page_id]", on_load=DynamicState.on_load_redir) # type: ignore + @rx.page(route="/redirect-page/[page_id]", on_load=DynamicState.on_load_redir) def redirect_page(): return rx.fragment(rx.text("redirecting...")) app = rx.App(_state=rx.State) - app.add_page(index, route="/page/[page_id]", on_load=DynamicState.on_load) # type: ignore - app.add_page(index, route="/static/x", on_load=DynamicState.on_load) # type: ignore + app.add_page(index, route="/page/[page_id]", on_load=DynamicState.on_load) + app.add_page(index, route="/static/x", on_load=DynamicState.on_load) app.add_page(index) - app.add_custom_404_page(on_load=DynamicState.on_load) # type: ignore + app.add_custom_404_page(on_load=DynamicState.on_load) @pytest.fixture(scope="module") diff --git a/tests/integration/test_event_actions.py b/tests/integration/test_event_actions.py index cc8e97b09fd..70741007508 100644 --- a/tests/integration/test_event_actions.py +++ b/tests/integration/test_event_actions.py @@ -63,16 +63,16 @@ def index(): rx.button( "Stop Prop Only", id="btn-stop-prop-only", - on_click=rx.stop_propagation, # type: ignore + on_click=rx.stop_propagation, # pyright: ignore [reportArgumentType] ), rx.button( "Click event", - on_click=EventActionState.on_click("no_event_actions"), # type: ignore + on_click=EventActionState.on_click("no_event_actions"), # pyright: ignore [reportCallIssue] id="btn-click-event", ), rx.button( "Click stop propagation", - on_click=EventActionState.on_click("stop_propagation").stop_propagation, # type: ignore + on_click=EventActionState.on_click("stop_propagation").stop_propagation, # pyright: ignore [reportCallIssue] id="btn-click-stop-propagation", ), rx.button( @@ -88,13 +88,13 @@ def index(): rx.link( "Link", href="#", - on_click=EventActionState.on_click("link_no_event_actions"), # type: ignore + on_click=EventActionState.on_click("link_no_event_actions"), # pyright: ignore [reportCallIssue] id="link", ), rx.link( "Link Stop Propagation", href="#", - on_click=EventActionState.on_click( # type: ignore + on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] "link_stop_propagation" ).stop_propagation, id="link-stop-propagation", @@ -102,13 +102,13 @@ def index(): rx.link( "Link Prevent Default Only", href="/invalid", - on_click=rx.prevent_default, # type: ignore + on_click=rx.prevent_default, # pyright: ignore [reportArgumentType] id="link-prevent-default-only", ), rx.link( "Link Prevent Default", href="/invalid", - on_click=EventActionState.on_click( # type: ignore + on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] "link_prevent_default" ).prevent_default, id="link-prevent-default", @@ -116,44 +116,44 @@ def index(): rx.link( "Link Both", href="/invalid", - on_click=EventActionState.on_click( # type: ignore + on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] "link_both" ).stop_propagation.prevent_default, id="link-stop-propagation-prevent-default", ), EventFiringComponent.create( id="custom-stop-propagation", - on_click=EventActionState.on_click( # type: ignore + on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] "custom-stop-propagation" ).stop_propagation, ), EventFiringComponent.create( id="custom-prevent-default", - on_click=EventActionState.on_click( # type: ignore + on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue] "custom-prevent-default" ).prevent_default, ), rx.button( "Throttle", id="btn-throttle", - on_click=lambda: EventActionState.on_click_throttle.throttle( + on_click=lambda: EventActionState.on_click_throttle.throttle( # pyright: ignore [reportFunctionMemberAccess] 200 ).stop_propagation, ), rx.button( "Debounce", id="btn-debounce", - on_click=EventActionState.on_click_debounce.debounce( + on_click=EventActionState.on_click_debounce.debounce( # pyright: ignore [reportFunctionMemberAccess] 200 ).stop_propagation, ), - rx.list( # type: ignore + rx.list( # pyright: ignore [reportAttributeAccessIssue] rx.foreach( - EventActionState.order, # type: ignore + EventActionState.order, rx.list_item, ), ), - on_click=EventActionState.on_click("outer"), # type: ignore + on_click=EventActionState.on_click("outer"), # pyright: ignore [reportCallIssue] ) app = rx.App(_state=rx.State) diff --git a/tests/integration/test_event_chain.py b/tests/integration/test_event_chain.py index 5a933253a68..df571e884ec 100644 --- a/tests/integration/test_event_chain.py +++ b/tests/integration/test_event_chain.py @@ -43,32 +43,32 @@ def event_arg_repr_type(self, arg): def event_nested_1(self): self.event_order.append("event_nested_1") yield State.event_nested_2 - yield State.event_arg("nested_1") # type: ignore + yield State.event_arg("nested_1") @rx.event def event_nested_2(self): self.event_order.append("event_nested_2") yield State.event_nested_3 yield rx.console_log("event_nested_2") - yield State.event_arg("nested_2") # type: ignore + yield State.event_arg("nested_2") @rx.event def event_nested_3(self): self.event_order.append("event_nested_3") yield State.event_no_args - yield State.event_arg("nested_3") # type: ignore + yield State.event_arg("nested_3") @rx.event def on_load_return_chain(self): self.event_order.append("on_load_return_chain") - return [State.event_arg(1), State.event_arg(2), State.event_arg(3)] # type: ignore + return [State.event_arg(1), State.event_arg(2), State.event_arg(3)] @rx.event def on_load_yield_chain(self): self.event_order.append("on_load_yield_chain") - yield State.event_arg(4) # type: ignore - yield State.event_arg(5) # type: ignore - yield State.event_arg(6) # type: ignore + yield State.event_arg(4) + yield State.event_arg(5) + yield State.event_arg(6) @rx.event def click_return_event(self): @@ -79,28 +79,28 @@ def click_return_event(self): def click_return_events(self): self.event_order.append("click_return_events") return [ - State.event_arg(7), # type: ignore + State.event_arg(7), rx.console_log("click_return_events"), - State.event_arg(8), # type: ignore - State.event_arg(9), # type: ignore + State.event_arg(8), + State.event_arg(9), ] @rx.event def click_yield_chain(self): self.event_order.append("click_yield_chain:0") - yield State.event_arg(10) # type: ignore + yield State.event_arg(10) self.event_order.append("click_yield_chain:1") yield rx.console_log("click_yield_chain") - yield State.event_arg(11) # type: ignore + yield State.event_arg(11) self.event_order.append("click_yield_chain:2") - yield State.event_arg(12) # type: ignore + yield State.event_arg(12) self.event_order.append("click_yield_chain:3") @rx.event def click_yield_many_events(self): self.event_order.append("click_yield_many_events") for ix in range(MANY_EVENTS): - yield State.event_arg(ix) # type: ignore + yield State.event_arg(ix) yield rx.console_log(f"many_events_{ix}") self.event_order.append("click_yield_many_events_done") @@ -108,7 +108,7 @@ def click_yield_many_events(self): def click_yield_nested(self): self.event_order.append("click_yield_nested") yield State.event_nested_1 - yield State.event_arg("yield_nested") # type: ignore + yield State.event_arg("yield_nested") @rx.event def redirect_return_chain(self): @@ -123,12 +123,12 @@ def redirect_yield_chain(self): @rx.event def click_return_int_type(self): self.event_order.append("click_return_int_type") - return State.event_arg_repr_type(1) # type: ignore + return State.event_arg_repr_type(1) @rx.event def click_return_dict_type(self): self.event_order.append("click_return_dict_type") - return State.event_arg_repr_type({"a": 1}) # type: ignore + return State.event_arg_repr_type({"a": 1}) @rx.event async def click_yield_interim_value_async(self): @@ -193,12 +193,12 @@ def index(): rx.button( "Click Int Type", id="click_int_type", - on_click=lambda: State.event_arg_repr_type(1), # type: ignore + on_click=lambda: State.event_arg_repr_type(1), ), rx.button( "Click Dict Type", id="click_dict_type", - on_click=lambda: State.event_arg_repr_type({"a": 1}), # type: ignore + on_click=lambda: State.event_arg_repr_type({"a": 1}), ), rx.button( "Return Chain Int Type", @@ -239,7 +239,7 @@ def on_mount_return_chain(): rx.text( "return", on_mount=State.on_load_return_chain, - on_unmount=lambda: State.event_arg("unmount"), # type: ignore + on_unmount=lambda: State.event_arg("unmount"), ), token_input, rx.button("Unmount", on_click=rx.redirect("/"), id="unmount"), @@ -251,7 +251,7 @@ def on_mount_yield_chain(): "yield", on_mount=[ State.on_load_yield_chain, - lambda: State.event_arg("mount"), # type: ignore + lambda: State.event_arg("mount"), ], on_unmount=State.event_no_args, ), @@ -259,8 +259,8 @@ def on_mount_yield_chain(): rx.button("Unmount", on_click=rx.redirect("/"), id="unmount"), ) - app.add_page(on_load_return_chain, on_load=State.on_load_return_chain) # type: ignore - app.add_page(on_load_yield_chain, on_load=State.on_load_yield_chain) # type: ignore + app.add_page(on_load_return_chain, on_load=State.on_load_return_chain) + app.add_page(on_load_yield_chain, on_load=State.on_load_yield_chain) app.add_page(on_mount_return_chain) app.add_page(on_mount_yield_chain) diff --git a/tests/integration/test_exception_handlers.py b/tests/integration/test_exception_handlers.py index 4d15bbf0186..71858b8995b 100644 --- a/tests/integration/test_exception_handlers.py +++ b/tests/integration/test_exception_handlers.py @@ -51,12 +51,12 @@ def index(): ), rx.button( "induce_backend_error", - on_click=lambda: TestAppState.divide_by_number(0), # type: ignore + on_click=lambda: TestAppState.divide_by_number(0), # pyright: ignore [reportCallIssue] id="induce-backend-error-btn", ), rx.button( "induce_react_error", - on_click=TestAppState.set_react_error(True), # type: ignore + on_click=TestAppState.set_react_error(True), # pyright: ignore [reportAttributeAccessIssue] id="induce-react-error-btn", ), rx.box( diff --git a/tests/integration/test_input.py b/tests/integration/test_input.py index bddeca45f11..5f2948feb7a 100644 --- a/tests/integration/test_input.py +++ b/tests/integration/test_input.py @@ -26,11 +26,11 @@ def index(): ), rx.input( id="debounce_input_input", - on_change=State.set_text, # type: ignore + on_change=State.set_text, # pyright: ignore [reportAttributeAccessIssue] value=State.text, ), rx.input(value=State.text, id="value_input", is_read_only=True), - rx.input(on_change=State.set_text, id="on_change_input"), # type: ignore + rx.input(on_change=State.set_text, id="on_change_input"), # pyright: ignore [reportAttributeAccessIssue] rx.el.input( value=State.text, id="plain_value_input", diff --git a/tests/integration/test_lifespan.py b/tests/integration/test_lifespan.py index d79273fbc53..24dd7df6af0 100644 --- a/tests/integration/test_lifespan.py +++ b/tests/integration/test_lifespan.py @@ -65,7 +65,7 @@ def index(): rx.moment( interval=LifespanState.interval, on_change=LifespanState.tick ), - on_click=LifespanState.set_interval( # type: ignore + on_click=LifespanState.set_interval( # pyright: ignore [reportAttributeAccessIssue] rx.cond(LifespanState.interval, 0, 100) ), id="toggle-tick", @@ -113,13 +113,13 @@ async def test_lifespan(lifespan_app: AppHarness): task_global = driver.find_element(By.ID, "task_global") assert context_global.text == "2" - assert lifespan_app.app_module.lifespan_context_global == 2 # type: ignore + assert lifespan_app.app_module.lifespan_context_global == 2 original_task_global_text = task_global.text original_task_global_value = int(original_task_global_text) lifespan_app.poll_for_content(task_global, exp_not_equal=original_task_global_text) driver.find_element(By.ID, "toggle-tick").click() # avoid teardown errors - assert lifespan_app.app_module.lifespan_task_global > original_task_global_value # type: ignore + assert lifespan_app.app_module.lifespan_task_global > original_task_global_value assert int(task_global.text) > original_task_global_value # Kill the backend diff --git a/tests/integration/test_login_flow.py b/tests/integration/test_login_flow.py index 7eb46ab39f9..a1df015bf49 100644 --- a/tests/integration/test_login_flow.py +++ b/tests/integration/test_login_flow.py @@ -31,8 +31,8 @@ def login(self): yield rx.redirect("/") def index(): - return rx.cond( - State.is_hydrated & State.auth_token, # type: ignore + return rx.cond( # pyright: ignore [reportCallIssue] + State.is_hydrated & State.auth_token, # pyright: ignore [reportOperatorIssue] 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_media.py b/tests/integration/test_media.py index 649038a7e1b..f3ce65c8787 100644 --- a/tests/integration/test_media.py +++ b/tests/integration/test_media.py @@ -19,7 +19,7 @@ class State(rx.State): def _blue(self, format=None) -> Image.Image: img = Image.new("RGB", (200, 200), "blue") if format is not None: - img.format = format # type: ignore + img.format = format return img @rx.var @@ -50,7 +50,7 @@ def img_webp(self) -> Image.Image: def img_from_url(self) -> Image.Image: img_url = "https://picsum.photos/id/1/200/300" img_resp = httpx.get(img_url, follow_redirects=True) - return Image.open(img_resp) # type: ignore + return Image.open(img_resp) # pyright: ignore [reportArgumentType] app = rx.App() diff --git a/tests/integration/test_state_inheritance.py b/tests/integration/test_state_inheritance.py index 6b93a2ed738..f544fcc92af 100644 --- a/tests/integration/test_state_inheritance.py +++ b/tests/integration/test_state_inheritance.py @@ -131,7 +131,7 @@ def index() -> rx.Component: rx.heading(Base1.child_mixin, id="base1-child-mixin"), rx.button( "Base1.on_click_mixin", - on_click=Base1.on_click_mixin, # type: ignore + on_click=Base1.on_click_mixin, id="base1-mixin-btn", ), rx.heading( @@ -153,7 +153,7 @@ def index() -> rx.Component: rx.heading(Child1.child_mixin, id="child1-child-mixin"), rx.button( "Child1.on_click_other_mixin", - on_click=Child1.on_click_other_mixin, # type: ignore + on_click=Child1.on_click_other_mixin, id="child1-other-mixin-btn", ), # Child 2 (Mixin, ChildMixin, OtherMixin) @@ -166,12 +166,12 @@ def index() -> rx.Component: rx.heading(Child2.child_mixin, id="child2-child-mixin"), rx.button( "Child2.on_click_mixin", - on_click=Child2.on_click_mixin, # type: ignore + on_click=Child2.on_click_mixin, id="child2-mixin-btn", ), rx.button( "Child2.on_click_other_mixin", - on_click=Child2.on_click_other_mixin, # type: ignore + on_click=Child2.on_click_other_mixin, id="child2-other-mixin-btn", ), # Child 3 (Mixin, ChildMixin, OtherMixin) @@ -186,12 +186,12 @@ def index() -> rx.Component: rx.heading(Child3.child_mixin, id="child3-child-mixin"), rx.button( "Child3.on_click_mixin", - on_click=Child3.on_click_mixin, # type: ignore + on_click=Child3.on_click_mixin, id="child3-mixin-btn", ), rx.button( "Child3.on_click_other_mixin", - on_click=Child3.on_click_other_mixin, # type: ignore + on_click=Child3.on_click_other_mixin, id="child3-other-mixin-btn", ), rx.heading( diff --git a/tests/integration/test_upload.py b/tests/integration/test_upload.py index 07c3997b4a0..a0df05f52fe 100644 --- a/tests/integration/test_upload.py +++ b/tests/integration/test_upload.py @@ -80,7 +80,7 @@ def index(): ), rx.button( "Upload", - on_click=lambda: UploadState.handle_upload(rx.upload_files()), # type: ignore + on_click=lambda: UploadState.handle_upload(rx.upload_files()), # pyright: ignore [reportCallIssue] id="upload_button", ), rx.box( @@ -105,7 +105,7 @@ def index(): ), rx.button( "Upload", - on_click=UploadState.handle_upload_secondary( # type: ignore + on_click=UploadState.handle_upload_secondary( # pyright: ignore [reportCallIssue] rx.upload_files( upload_id="secondary", on_upload_progress=UploadState.upload_progress, @@ -127,7 +127,7 @@ def index(): ), rx.vstack( rx.foreach( - UploadState.progress_dicts, # type: ignore + UploadState.progress_dicts, lambda d: rx.text(d.to_string()), ) ), @@ -146,7 +146,7 @@ def index(): ), rx.button( "Upload", - on_click=UploadState.handle_upload_tertiary( # type: ignore + on_click=UploadState.handle_upload_tertiary( # pyright: ignore [reportCallIssue] rx.upload_files( upload_id="tertiary", ), diff --git a/tests/integration/test_var_operations.py b/tests/integration/test_var_operations.py index 86d68340aeb..a09c8612ef6 100644 --- a/tests/integration/test_var_operations.py +++ b/tests/integration/test_var_operations.py @@ -7,42 +7,38 @@ from reflex.testing import AppHarness -# pyright: reportOptionalMemberAccess=false, reportGeneralTypeIssues=false, reportUnknownMemberType=false - def VarOperations(): """App with var operations.""" - from typing import Dict, List - import reflex as rx from reflex.vars.base import LiteralVar from reflex.vars.sequence import ArrayVar class Object(rx.Base): - str: str = "hello" + name: str = "hello" class VarOperationState(rx.State): - int_var1: int = 10 - int_var2: int = 5 - int_var3: int = 7 - float_var1: float = 10.5 - float_var2: float = 5.5 - list1: List = [1, 2] - list2: List = [3, 4] - list3: List = ["first", "second", "third"] - list4: List = [Object(name="obj_1"), Object(name="obj_2")] - str_var1: str = "first" - str_var2: str = "second" - str_var3: str = "ThIrD" - str_var4: str = "a long string" - dict1: Dict[int, int] = {1: 2} - dict2: Dict[int, int] = {3: 4} - html_str: str = "
hello
" + int_var1: rx.Field[int] = rx.field(10) + int_var2: rx.Field[int] = rx.field(5) + int_var3: rx.Field[int] = rx.field(7) + float_var1: rx.Field[float] = rx.field(10.5) + float_var2: rx.Field[float] = rx.field(5.5) + list1: rx.Field[list] = rx.field([1, 2]) + list2: rx.Field[list] = rx.field([3, 4]) + list3: rx.Field[list] = rx.field(["first", "second", "third"]) + list4: rx.Field[list] = rx.field([Object(name="obj_1"), Object(name="obj_2")]) + str_var1: rx.Field[str] = rx.field("first") + str_var2: rx.Field[str] = rx.field("second") + str_var3: rx.Field[str] = rx.field("ThIrD") + str_var4: rx.Field[str] = rx.field("a long string") + dict1: rx.Field[dict[int, int]] = rx.field({1: 2}) + dict2: rx.Field[dict[int, int]] = rx.field({3: 4}) + html_str: rx.Field[str] = rx.field("
hello
") app = rx.App(_state=rx.State) @rx.memo - def memo_comp(list1: List[int], int_var1: int, id: str): + def memo_comp(list1: list[int], int_var1: int, id: str): return rx.text(list1, int_var1, id=id) @rx.memo @@ -378,7 +374,8 @@ def index(): id="str_contains", ), rx.text( - VarOperationState.str_var1 | VarOperationState.str_var1, id="str_or_str" + VarOperationState.str_var1 | VarOperationState.str_var1, + id="str_or_str", ), rx.text( VarOperationState.str_var1 & VarOperationState.str_var2, @@ -394,7 +391,8 @@ def index(): id="str_and_int", ), rx.text( - VarOperationState.str_var1 | VarOperationState.int_var2, id="str_or_int" + VarOperationState.str_var1 | VarOperationState.int_var2, + id="str_or_int", ), rx.text( (VarOperationState.str_var1 == VarOperationState.int_var1).to_string(), @@ -406,7 +404,8 @@ def index(): ), # STR, LIST rx.text( - VarOperationState.str_var1 | VarOperationState.list1, id="str_or_list" + VarOperationState.str_var1 | VarOperationState.list1, + id="str_or_list", ), rx.text( (VarOperationState.str_var1 & VarOperationState.list1).to_string(), @@ -422,7 +421,8 @@ def index(): ), # STR, DICT rx.text( - VarOperationState.str_var1 | VarOperationState.dict1, id="str_or_dict" + VarOperationState.str_var1 | VarOperationState.dict1, + id="str_or_dict", ), rx.text( (VarOperationState.str_var1 & VarOperationState.dict1).to_string(), @@ -474,7 +474,8 @@ def index(): id="list_neq_list", ), rx.text( - VarOperationState.list1.contains(1).to_string(), id="list_contains" + VarOperationState.list1.contains(1).to_string(), + id="list_contains", ), rx.text(VarOperationState.list4.pluck("name").to_string(), id="list_pluck"), rx.text(VarOperationState.list1.reverse().to_string(), id="list_reverse"), @@ -534,7 +535,8 @@ def index(): id="dict_neq_dict", ), rx.text( - VarOperationState.dict1.contains(1).to_string(), id="dict_contains" + VarOperationState.dict1.contains(1).to_string(), + id="dict_contains", ), rx.text(VarOperationState.str_var3.lower(), id="str_lower"), rx.text(VarOperationState.str_var3.upper(), id="str_upper"), @@ -571,7 +573,7 @@ def index(): ), rx.box( rx.foreach( - LiteralVar.create(list(range(0, 3))).to(ArrayVar, List[int]), + LiteralVar.create(list(range(0, 3))).to(ArrayVar, list[int]), lambda x: rx.foreach( ArrayVar.range(x), lambda y: rx.text(VarOperationState.list1[y], as_="p"), diff --git a/tests/integration/tests_playwright/test_appearance.py b/tests/integration/tests_playwright/test_appearance.py index 60aeeaa6b51..d325b183fea 100644 --- a/tests/integration/tests_playwright/test_appearance.py +++ b/tests/integration/tests_playwright/test_appearance.py @@ -85,7 +85,7 @@ def light_mode_app(tmp_path_factory) -> Generator[AppHarness, None, None]: """ with AppHarness.create( root=tmp_path_factory.mktemp("appearance_app"), - app_source=DefaultLightModeApp, # type: ignore + app_source=DefaultLightModeApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness @@ -104,7 +104,7 @@ def dark_mode_app(tmp_path_factory) -> Generator[AppHarness, None, None]: """ with AppHarness.create( root=tmp_path_factory.mktemp("appearance_app"), - app_source=DefaultDarkModeApp, # type: ignore + app_source=DefaultDarkModeApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness @@ -123,7 +123,7 @@ def system_mode_app(tmp_path_factory) -> Generator[AppHarness, None, None]: """ with AppHarness.create( root=tmp_path_factory.mktemp("appearance_app"), - app_source=DefaultSystemModeApp, # type: ignore + app_source=DefaultSystemModeApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness @@ -142,7 +142,7 @@ def color_toggle_app(tmp_path_factory) -> Generator[AppHarness, None, None]: """ with AppHarness.create( root=tmp_path_factory.mktemp("appearance_app"), - app_source=ColorToggleApp, # type: ignore + app_source=ColorToggleApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness diff --git a/tests/integration/tests_playwright/test_datetime_operations.py b/tests/integration/tests_playwright/test_datetime_operations.py index 5e45067760a..2ac516d4acb 100644 --- a/tests/integration/tests_playwright/test_datetime_operations.py +++ b/tests/integration/tests_playwright/test_datetime_operations.py @@ -54,7 +54,7 @@ def datetime_operations_app(tmp_path_factory) -> Generator[AppHarness, None, Non """ with AppHarness.create( root=tmp_path_factory.mktemp("datetime_operations_app"), - app_source=DatetimeOperationsApp, # type: ignore + app_source=DatetimeOperationsApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness diff --git a/tests/integration/tests_playwright/test_link_hover.py b/tests/integration/tests_playwright/test_link_hover.py index 9510bd3587c..3c29d769ab4 100644 --- a/tests/integration/tests_playwright/test_link_hover.py +++ b/tests/integration/tests_playwright/test_link_hover.py @@ -29,7 +29,7 @@ def index(): def link_app(tmp_path_factory) -> Generator[AppHarness, None, None]: with AppHarness.create( root=tmp_path_factory.mktemp("link_app"), - app_source=LinkApp, # type: ignore + app_source=LinkApp, ) as harness: assert harness.app_instance is not None, "app is not running" yield harness diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 25c351c019b..50088e728d8 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -92,7 +92,7 @@ def test_compile_import_statement( ), ], ) -def test_compile_imports(import_dict: ParsedImportDict, test_dicts: List[dict]): +def test_compile_imports(import_dict: ParsedImportDict, test_dicts: list[dict]): """Test the compile_imports function. Args: @@ -103,7 +103,7 @@ def test_compile_imports(import_dict: ParsedImportDict, test_dicts: List[dict]): for import_dict, test_dict in zip(imports, test_dicts, strict=True): assert import_dict["lib"] == test_dict["lib"] assert import_dict["default"] == test_dict["default"] - assert sorted(import_dict["rest"]) == test_dict["rest"] # type: ignore + assert sorted(import_dict["rest"]) == test_dict["rest"] # pyright: ignore [reportArgumentType] def test_compile_stylesheets(tmp_path, mocker): @@ -198,7 +198,7 @@ def test_create_document_root(): assert isinstance(root, utils.Html) assert isinstance(root.children[0], utils.DocumentHead) # Default language. - assert root.lang == "en" # type: ignore + assert root.lang == "en" # pyright: ignore [reportAttributeAccessIssue] # No children in head. assert len(root.children[0].children) == 0 @@ -208,13 +208,13 @@ def test_create_document_root(): utils.NextScript.create(src="bar.js"), ] root = utils.create_document_root( - head_components=comps, # type: ignore + head_components=comps, # pyright: ignore [reportArgumentType] html_lang="rx", html_custom_attrs={"project": "reflex"}, ) # Two children in head. assert isinstance(root, utils.Html) assert len(root.children[0].children) == 2 - assert root.lang == "rx" # type: ignore + assert root.lang == "rx" # pyright: ignore [reportAttributeAccessIssue] assert isinstance(root.custom_attrs, dict) assert root.custom_attrs == {"project": "reflex"} diff --git a/tests/units/components/core/test_colors.py b/tests/units/components/core/test_colors.py index c1295fb4158..15490e5762b 100644 --- a/tests/units/components/core/test_colors.py +++ b/tests/units/components/core/test_colors.py @@ -31,37 +31,37 @@ def create_color_var(color): (create_color_var(rx.color("mint", 3)), '"var(--mint-3)"', Color), (create_color_var(rx.color("mint", 3, True)), '"var(--mint-a3)"', Color), ( - create_color_var(rx.color(ColorState.color, ColorState.shade)), # type: ignore + create_color_var(rx.color(ColorState.color, ColorState.shade)), # pyright: ignore [reportArgumentType] f'("var(--"+{color_state_name!s}.color+"-"+(((__to_string) => __to_string.toString())({color_state_name!s}.shade))+")")', Color, ), ( create_color_var( - rx.color(ColorState.color, ColorState.shade, ColorState.alpha) # type: ignore + rx.color(ColorState.color, ColorState.shade, ColorState.alpha) # pyright: ignore [reportArgumentType] ), f'("var(--"+{color_state_name!s}.color+"-"+({color_state_name!s}.alpha ? "a" : "")+(((__to_string) => __to_string.toString())({color_state_name!s}.shade))+")")', Color, ), ( - create_color_var(rx.color(f"{ColorState.color}", f"{ColorState.shade}")), # type: ignore + create_color_var(rx.color(f"{ColorState.color}", f"{ColorState.shade}")), # pyright: ignore [reportArgumentType] f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")', Color, ), ( create_color_var( - rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}") # type: ignore + rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}") # pyright: ignore [reportArgumentType] ), f'("var(--"+({color_state_name!s}.color_part+"ato")+"-"+{color_state_name!s}.shade+")")', Color, ), ( - create_color_var(f'{rx.color(ColorState.color, f"{ColorState.shade}")}'), # type: ignore + create_color_var(f'{rx.color(ColorState.color, f"{ColorState.shade}")}'), # pyright: ignore [reportArgumentType] f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")', str, ), ( create_color_var( - f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}' # type: ignore + f'{rx.color(f"{ColorState.color}", f"{ColorState.shade}")}' # pyright: ignore [reportArgumentType] ), f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")', str, @@ -81,7 +81,7 @@ def test_color(color, expected, expected_type: Union[Type[str], Type[Color]]): '(true ? "var(--mint-7)" : "var(--tomato-5)")', ), ( - rx.cond(True, rx.color(ColorState.color), rx.color(ColorState.color, 5)), # type: ignore + rx.cond(True, rx.color(ColorState.color), rx.color(ColorState.color, 5)), # pyright: ignore [reportArgumentType, reportCallIssue] f'(true ? ("var(--"+{color_state_name!s}.color+"-7)") : ("var(--"+{color_state_name!s}.color+"-5)"))', ), ( @@ -89,7 +89,7 @@ def test_color(color, expected, expected_type: Union[Type[str], Type[Color]]): "condition", ("first", rx.color("mint")), ("second", rx.color("tomato", 5)), - rx.color(ColorState.color, 2), # type: ignore + rx.color(ColorState.color, 2), # pyright: ignore [reportArgumentType] ), '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"): return ("var(--mint-7)");' ' break;case JSON.stringify("second"): return ("var(--tomato-5)"); break;default: ' @@ -98,9 +98,9 @@ def test_color(color, expected, expected_type: Union[Type[str], Type[Color]]): ( rx.match( "condition", - ("first", rx.color(ColorState.color)), # type: ignore - ("second", rx.color(ColorState.color, 5)), # type: ignore - rx.color(ColorState.color, 2), # type: ignore + ("first", rx.color(ColorState.color)), # pyright: ignore [reportArgumentType] + ("second", rx.color(ColorState.color, 5)), # pyright: ignore [reportArgumentType] + rx.color(ColorState.color, 2), # pyright: ignore [reportArgumentType] ), '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"): ' f'return (("var(--"+{color_state_name!s}.color+"-7)")); break;case JSON.stringify("second"): ' @@ -133,4 +133,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 # type: ignore + assert str(code_block.custom_style["backgroundColor"]) == expected # pyright: ignore [reportAttributeAccessIssue] diff --git a/tests/units/components/core/test_cond.py b/tests/units/components/core/test_cond.py index e88f35c9a7d..ac073ed29bc 100644 --- a/tests/units/components/core/test_cond.py +++ b/tests/units/components/core/test_cond.py @@ -14,7 +14,7 @@ @pytest.fixture def cond_state(request): class CondState(BaseState): - value: request.param["value_type"] = request.param["value"] # noqa + value: request.param["value_type"] = request.param["value"] # pyright: ignore [reportInvalidTypeForm, reportUndefinedVariable] # noqa: F821 return CondState @@ -112,13 +112,13 @@ def test_cond_no_else(): assert isinstance(comp, Fragment) comp = comp.children[0] assert isinstance(comp, Cond) - assert comp.cond._decode() is True # type: ignore - assert comp.comp1.render() == Fragment.create(Text.create("hello")).render() + assert comp.cond._decode() is True + assert comp.comp1.render() == Fragment.create(Text.create("hello")).render() # pyright: ignore [reportOptionalMemberAccess] assert comp.comp2 == Fragment.create() # Props do not support the use of cond without else with pytest.raises(ValueError): - cond(True, "hello") # type: ignore + cond(True, "hello") # pyright: ignore [reportArgumentType] def test_cond_computed_var(): diff --git a/tests/units/components/core/test_html.py b/tests/units/components/core/test_html.py index 79c258dfbb6..bebb2587d91 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 !

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

Hello !

" })' # pyright: ignore [reportAttributeAccessIssue] assert ( str(html) == '
Hello !

" })}/>' @@ -32,10 +32,10 @@ class TestState(State): html = Html.create(f"

Hello {TestState.myvar}!

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

Hello "+{TestState.myvar!s}+"!

") }})' ) assert ( str(html) - == f'
' # type: ignore + == f'
' # pyright: ignore [reportAttributeAccessIssue] ) diff --git a/tests/units/components/core/test_match.py b/tests/units/components/core/test_match.py index eaf98414d7b..e563873ec83 100644 --- a/tests/units/components/core/test_match.py +++ b/tests/units/components/core/test_match.py @@ -29,7 +29,7 @@ def test_match_components(): rx.text("default value"), ) match_comp = Match.create(MatchState.value, *match_case_tuples) - match_dict = match_comp.render() # type: ignore + match_dict = match_comp.render() assert match_dict["name"] == "Fragment" [match_child] = match_dict["children"] @@ -151,7 +151,7 @@ def test_match_on_component_without_default(): ) match_comp = Match.create(MatchState.value, *match_case_tuples) - default = match_comp.render()["children"][0]["default"] # type: ignore + default = match_comp.render()["children"][0]["default"] assert isinstance(default, Fragment) diff --git a/tests/units/components/core/test_upload.py b/tests/units/components/core/test_upload.py index 710baa161e4..efade7b63f3 100644 --- a/tests/units/components/core/test_upload.py +++ b/tests/units/components/core/test_upload.py @@ -5,7 +5,7 @@ StyledUpload, Upload, UploadNamespace, - _on_drop_spec, # type: ignore + _on_drop_spec, # pyright: ignore [reportAttributeAccessIssue] cancel_upload, get_upload_url, ) @@ -60,7 +60,7 @@ def test_upload_create(): up_comp_2 = Upload.create( id="foo_id", - on_drop=UploadStateTest.drop_handler([]), # type: ignore + on_drop=UploadStateTest.drop_handler([]), ) assert isinstance(up_comp_2, Upload) assert up_comp_2.is_used @@ -80,7 +80,7 @@ def test_upload_create(): up_comp_4 = Upload.create( id="foo_id", - on_drop=UploadStateTest.not_drop_handler([]), # type: ignore + on_drop=UploadStateTest.not_drop_handler([]), ) assert isinstance(up_comp_4, Upload) assert up_comp_4.is_used @@ -96,7 +96,7 @@ def test_styled_upload_create(): styled_up_comp_2 = StyledUpload.create( id="foo_id", - on_drop=UploadStateTest.drop_handler([]), # type: ignore + on_drop=UploadStateTest.drop_handler([]), ) assert isinstance(styled_up_comp_2, StyledUpload) assert styled_up_comp_2.is_used @@ -116,7 +116,7 @@ def test_styled_upload_create(): styled_up_comp_4 = StyledUpload.create( id="foo_id", - on_drop=UploadStateTest.not_drop_handler([]), # type: ignore + on_drop=UploadStateTest.not_drop_handler([]), ) assert isinstance(styled_up_comp_4, StyledUpload) assert styled_up_comp_4.is_used diff --git a/tests/units/components/datadisplay/test_code.py b/tests/units/components/datadisplay/test_code.py index 6b7168756bf..db0120fe1c1 100644 --- a/tests/units/components/datadisplay/test_code.py +++ b/tests/units/components/datadisplay/test_code.py @@ -10,4 +10,4 @@ def test_code_light_dark_theme(theme, expected): code_block = CodeBlock.create(theme=theme) - assert code_block.theme._js_expr == expected # type: ignore + assert code_block.theme._js_expr == expected # pyright: ignore [reportAttributeAccessIssue] diff --git a/tests/units/components/datadisplay/test_datatable.py b/tests/units/components/datadisplay/test_datatable.py index a8f966d7e6e..2dece464afa 100644 --- a/tests/units/components/datadisplay/test_datatable.py +++ b/tests/units/components/datadisplay/test_datatable.py @@ -14,7 +14,8 @@ pytest.param( { "data": pd.DataFrame( - [["foo", "bar"], ["foo1", "bar1"]], columns=["column1", "column2"] + [["foo", "bar"], ["foo1", "bar1"]], + columns=["column1", "column2"], # pyright: ignore [reportArgumentType] ) }, "data", @@ -114,7 +115,8 @@ def test_computed_var_without_annotation(fixture, request, err_msg, is_data_fram def test_serialize_dataframe(): """Test if dataframe is serialized correctly.""" df = pd.DataFrame( - [["foo", "bar"], ["foo1", "bar1"]], columns=["column1", "column2"] + [["foo", "bar"], ["foo1", "bar1"]], + columns=["column1", "column2"], # pyright: ignore [reportArgumentType] ) value = serialize(df) assert value == serialize_dataframe(df) diff --git a/tests/units/components/datadisplay/test_shiki_code.py b/tests/units/components/datadisplay/test_shiki_code.py index eb473ba06d6..cc05c35b074 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 # type: ignore + assert code_block_component.code._var_value == expected_first_child # pyright: ignore [reportAttributeAccessIssue] applied_styles = component.style for key, value in expected_styles.items(): @@ -128,12 +128,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] # type: ignore + assert code_block_component.code._var_value == children[0] # pyright: ignore [reportAttributeAccessIssue] # 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: # type: ignore + for transformer in code_block_component.transformers._var_value: # pyright: ignore [reportAttributeAccessIssue] assert type(transformer).__name__ in exp_trans_names # Check if the second child is the copy button if can_copy is True @@ -161,12 +161,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"]) # type: ignore + ].theme._var_value == ShikiHighLevelCodeBlock._map_themes(props["theme"]) # pyright: ignore [reportAttributeAccessIssue] # Test that the language is mapped correctly if "language" in props: assert component.children[ 0 - ].language._var_value == ShikiHighLevelCodeBlock._map_languages( # type: ignore + ].language._var_value == ShikiHighLevelCodeBlock._map_languages( # pyright: ignore [reportAttributeAccessIssue] props["language"] ) diff --git a/tests/units/components/forms/test_form.py b/tests/units/components/forms/test_form.py index 5f3ba2d37e3..69b5e7b6328 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}" # type: ignore + exp_submit_name = f"handleSubmit_{f.handle_submit_unique_name}" # pyright: ignore [reportAttributeAccessIssue] 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 742bd8c3814..519ca735e13 100644 --- a/tests/units/components/media/test_image.py +++ b/tests/units/components/media/test_image.py @@ -4,7 +4,7 @@ from PIL.Image import Image as Img import reflex as rx -from reflex.components.next.image import Image # type: ignore +from reflex.components.next.image import Image from reflex.utils.serializers import serialize, serialize_image from reflex.vars.sequence import StringVar @@ -17,7 +17,7 @@ def pil_image() -> Img: A random PIL image. """ imarray = np.random.rand(100, 100, 3) * 255 - return PIL.Image.fromarray(imarray.astype("uint8")).convert("RGBA") # type: ignore + return PIL.Image.fromarray(imarray.astype("uint8")).convert("RGBA") # pyright: ignore [reportAttributeAccessIssue] def test_serialize_image(pil_image: Img): @@ -36,13 +36,13 @@ def test_set_src_str(): """Test that setting the src works.""" image = rx.image(src="pic2.jpeg") # when using next/image, we explicitly create a _var_is_str Var - assert str(image.src) in ( # type: ignore + assert str(image.src) in ( # pyright: ignore [reportAttributeAccessIssue] '"pic2.jpeg"', "'pic2.jpeg'", "`pic2.jpeg`", ) # For plain rx.el.img, an explicit var is not created, so the quoting happens later - # assert str(image.src) == "pic2.jpeg" # type: ignore #noqa: ERA001 + # assert str(image.src) == "pic2.jpeg" #noqa: ERA001 def test_set_src_img(pil_image: Img): @@ -52,7 +52,7 @@ def test_set_src_img(pil_image: Img): pil_image: The image to serialize. """ image = Image.create(src=pil_image) - assert str(image.src._js_expr) == '"' + serialize_image(pil_image) + '"' # type: ignore + assert str(image.src._js_expr) == '"' + serialize_image(pil_image) + '"' # pyright: ignore [reportAttributeAccessIssue] def test_render(pil_image: Img): @@ -62,4 +62,4 @@ def test_render(pil_image: Img): pil_image: The image to serialize. """ image = Image.create(src=pil_image) - assert isinstance(image.src, StringVar) # type: ignore + assert isinstance(image.src, StringVar) # pyright: ignore [reportAttributeAccessIssue] diff --git a/tests/units/components/test_component.py b/tests/units/components/test_component.py index 6ea459142c3..26e530f7cb4 100644 --- a/tests/units/components/test_component.py +++ b/tests/units/components/test_component.py @@ -452,8 +452,8 @@ def test_add_style(component1, component2): component1: Style({"color": "white"}), component2: Style({"color": "black"}), } - c1 = component1()._add_style_recursive(style) # type: ignore - c2 = component2()._add_style_recursive(style) # type: ignore + c1 = component1()._add_style_recursive(style) + c2 = component2()._add_style_recursive(style) assert str(c1.style["color"]) == '"white"' assert str(c2.style["color"]) == '"black"' @@ -469,8 +469,8 @@ def test_add_style_create(component1, component2): component1.create: Style({"color": "white"}), component2.create: Style({"color": "black"}), } - c1 = component1()._add_style_recursive(style) # type: ignore - c2 = component2()._add_style_recursive(style) # type: ignore + c1 = component1()._add_style_recursive(style) + c2 = component2()._add_style_recursive(style) assert str(c1.style["color"]) == '"white"' assert str(c2.style["color"]) == '"black"' @@ -1363,17 +1363,17 @@ def handler2(self, arg): id="fstring-background_color", ), pytest.param( - rx.fragment(style={"background_color": TEST_VAR}), # type: ignore + rx.fragment(style={"background_color": TEST_VAR}), # pyright: ignore [reportArgumentType] [STYLE_VAR], id="direct-style-background_color", ), pytest.param( - rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # type: ignore + rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # pyright: ignore [reportArgumentType] [STYLE_VAR], id="fstring-style-background_color", ), pytest.param( - rx.fragment(on_click=EVENT_CHAIN_VAR), # type: ignore + rx.fragment(on_click=EVENT_CHAIN_VAR), [EVENT_CHAIN_VAR], id="direct-event-chain", ), @@ -1383,17 +1383,17 @@ def handler2(self, arg): id="direct-event-handler", ), pytest.param( - rx.fragment(on_click=EventState.handler2(TEST_VAR)), # type: ignore + rx.fragment(on_click=EventState.handler2(TEST_VAR)), # pyright: ignore [reportCallIssue] [ARG_VAR, TEST_VAR], id="direct-event-handler-arg", ), pytest.param( - rx.fragment(on_click=EventState.handler2(EventState.v)), # type: ignore + rx.fragment(on_click=EventState.handler2(EventState.v)), # pyright: ignore [reportCallIssue] [ARG_VAR, EventState.v], id="direct-event-handler-arg2", ), pytest.param( - rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # type: ignore + rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # pyright: ignore [reportCallIssue] [ARG_VAR, TEST_VAR], id="direct-event-handler-lambda", ), @@ -1482,7 +1482,7 @@ def test_instantiate_all_components(): comp_name for submodule_list in component_nested_list for comp_name in submodule_list - ]: # type: ignore + ]: if component_name in untested_components: continue component = getattr( @@ -1555,11 +1555,11 @@ def test_validate_valid_children(): ) valid_component1( - rx.cond( # type: ignore + rx.cond( True, rx.fragment(valid_component2()), rx.fragment( - rx.foreach(LiteralVar.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore + rx.foreach(LiteralVar.create([1, 2, 3]), lambda x: valid_component2(x)) ), ) ) @@ -1614,12 +1614,12 @@ def test_validate_valid_parents(): ) valid_component2( - rx.cond( # type: ignore + rx.cond( True, rx.fragment(valid_component3()), rx.fragment( rx.foreach( - LiteralVar.create([1, 2, 3]), # type: ignore + LiteralVar.create([1, 2, 3]), lambda x: valid_component2(valid_component3(x)), ) ), @@ -1682,13 +1682,13 @@ def test_validate_invalid_children(): with pytest.raises(ValueError): valid_component4( - rx.cond( # type: ignore + rx.cond( True, rx.fragment(invalid_component()), rx.fragment( rx.foreach( LiteralVar.create([1, 2, 3]), lambda x: invalid_component(x) - ) # type: ignore + ) ), ) ) @@ -1870,7 +1870,7 @@ def get_event_triggers(self) -> Dict[str, Any]: ) def test_component_add_imports(tags): class BaseComponent(Component): - def _get_imports(self) -> ImportDict: + def _get_imports(self) -> ImportDict: # pyright: ignore [reportIncompatibleMethodOverride] return {} class Reference(Component): @@ -1882,7 +1882,7 @@ def _get_imports(self) -> ParsedImportDict: ) class TestBase(Component): - def add_imports( + def add_imports( # pyright: ignore [reportIncompatibleMethodOverride] self, ) -> Dict[str, Union[str, ImportVar, List[str], List[ImportVar]]]: return {"foo": "bar"} @@ -1914,7 +1914,7 @@ class ChildComponent1(BaseComponent): pass class GrandchildComponent1(ChildComponent1): - def add_hooks(self): + def add_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] return [ "const hook2 = 43", "const hook3 = 44", @@ -1927,11 +1927,11 @@ def add_hooks(self): ] class GrandchildComponent2(ChildComponent1): - def _get_hooks(self): + def _get_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] return "const hook5 = 46" class GreatGrandchildComponent2(GrandchildComponent2): - def add_hooks(self): + def add_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] return [ "const hook2 = 43", "const hook6 = 47", @@ -2006,7 +2006,7 @@ def add_custom_code(self): ] class GrandchildComponent2(ChildComponent1): - def _get_custom_code(self): + def _get_custom_code(self): # pyright: ignore [reportIncompatibleMethodOverride] return "const custom_code5 = 46" class GreatGrandchildComponent2(GrandchildComponent2): @@ -2102,11 +2102,11 @@ def test_add_style_embedded_vars(test_state: BaseState): test_state: A test state. """ v0 = LiteralVar.create("parent")._replace( - merge_var_data=VarData(hooks={"useParent": None}), # type: ignore + merge_var_data=VarData(hooks={"useParent": None}), ) v1 = rx.color("plum", 10) v2 = LiteralVar.create("text")._replace( - merge_var_data=VarData(hooks={"useText": None}), # type: ignore + merge_var_data=VarData(hooks={"useText": None}), ) class ParentComponent(Component): @@ -2120,7 +2120,7 @@ def add_style(self): class StyledComponent(ParentComponent): tag = "StyledComponent" - def add_style(self): + def add_style(self): # pyright: ignore [reportIncompatibleMethodOverride] return { "color": v1, "fake": v2, diff --git a/tests/units/components/typography/test_markdown.py b/tests/units/components/typography/test_markdown.py index 5e9abbb1f3a..12f3b0dbe31 100644 --- a/tests/units/components/typography/test_markdown.py +++ b/tests/units/components/typography/test_markdown.py @@ -29,8 +29,8 @@ def test_get_component(tag, expected): expected: The expected component. """ md = Markdown.create("# Hello") - assert tag in md.component_map # type: ignore - assert md.get_component(tag).tag == expected # type: ignore + assert tag in md.component_map # pyright: ignore [reportAttributeAccessIssue] + assert md.get_component(tag).tag == expected def test_set_component_map(): @@ -42,8 +42,8 @@ def test_set_component_map(): md = Markdown.create("# Hello", component_map=component_map) # Check that the new tags have been added. - assert md.get_component("h1").tag == "Box" # type: ignore - assert md.get_component("p").tag == "Box" # type: ignore + assert md.get_component("h1").tag == "Box" + assert md.get_component("p").tag == "Box" # Make sure the old tags are still there. - assert md.get_component("h2").tag == "Heading" # type: ignore + assert md.get_component("h2").tag == "Heading" diff --git a/tests/units/conftest.py b/tests/units/conftest.py index 8c1ffe532a9..2ee290ea388 100644 --- a/tests/units/conftest.py +++ b/tests/units/conftest.py @@ -95,7 +95,7 @@ def upload_sub_state_event_spec(): Returns: Event Spec. """ - return EventSpec(handler=SubUploadState.handle_upload, upload=True) # type: ignore + return EventSpec(handler=SubUploadState.handle_upload, upload=True) # pyright: ignore [reportCallIssue] @pytest.fixture @@ -105,7 +105,7 @@ def upload_event_spec(): Returns: Event Spec. """ - return EventSpec(handler=UploadState.handle_upload1, upload=True) # type: ignore + return EventSpec(handler=UploadState.handle_upload1, upload=True) # pyright: ignore [reportCallIssue] @pytest.fixture @@ -143,7 +143,7 @@ def sqlite_db_config_values(base_db_config_values) -> Dict: @pytest.fixture -def router_data_headers() -> Dict[str, str]: +def router_data_headers() -> dict[str, str]: """Router data headers. Returns: @@ -170,7 +170,7 @@ def router_data_headers() -> Dict[str, str]: @pytest.fixture -def router_data(router_data_headers) -> Dict[str, str]: +def router_data(router_data_headers: dict[str, str]) -> dict[str, str | dict]: """Router data. Args: @@ -179,7 +179,7 @@ def router_data(router_data_headers) -> Dict[str, str]: Returns: Dict of router data. """ - return { # type: ignore + return { "pathname": "/", "query": {}, "token": "b181904c-3953-4a79-dc18-ae9518c22f05", diff --git a/tests/units/states/mutation.py b/tests/units/states/mutation.py index b05f558a1ac..ad658bbd02d 100644 --- a/tests/units/states/mutation.py +++ b/tests/units/states/mutation.py @@ -18,7 +18,7 @@ class DictMutationTestState(BaseState): def add_age(self): """Add an age to the dict.""" - self.details.update({"age": 20}) # type: ignore + self.details.update({"age": 20}) # pyright: ignore [reportCallIssue, reportArgumentType] def change_name(self): """Change the name in the dict.""" diff --git a/tests/units/test_app.py b/tests/units/test_app.py index 80e0be5fd30..074e7f2ef61 100644 --- a/tests/units/test_app.py +++ b/tests/units/test_app.py @@ -133,7 +133,7 @@ def test_model() -> Type[Model]: A default model. """ - class TestModel(Model, table=True): # type: ignore + class TestModel(Model, table=True): pass return TestModel @@ -147,7 +147,7 @@ def test_model_auth() -> Type[Model]: A default model. """ - class TestModelAuth(Model, table=True): # type: ignore + class TestModelAuth(Model, table=True): """A test model with auth.""" pass @@ -185,19 +185,19 @@ class TestAuthProvider(AuthProvider): login_path: str = "/login" logout_path: str = "/logout" - def login(self): + def login(self): # pyright: ignore [reportIncompatibleMethodOverride] """Login.""" pass - def is_authenticated(self): + def is_authenticated(self): # pyright: ignore [reportIncompatibleMethodOverride] """Is authenticated.""" pass - def get_admin_user(self): + def get_admin_user(self): # pyright: ignore [reportIncompatibleMethodOverride] """Get admin user.""" pass - def logout(self): + def logout(self): # pyright: ignore [reportIncompatibleMethodOverride] """Logout.""" pass @@ -419,7 +419,7 @@ async def test_initialize_with_state(test_state: Type[ATestState], token: str): # Get a state for a given token. state = await app.state_manager.get_state(_substate_key(token, test_state)) assert isinstance(state, test_state) - assert state.var == 0 # type: ignore + assert state.var == 0 if isinstance(app.state_manager, StateManagerRedis): await app.state_manager.close() @@ -441,8 +441,8 @@ async def test_set_and_get_state(test_state): # Get the default state for each token. state1 = await app.state_manager.get_state(token1) state2 = await app.state_manager.get_state(token2) - assert state1.var == 0 # type: ignore - assert state2.var == 0 # type: ignore + assert state1.var == 0 + assert state2.var == 0 # Set the vars to different values. state1.var = 1 @@ -453,8 +453,8 @@ async def test_set_and_get_state(test_state): # Get the states again and check the values. state1 = await app.state_manager.get_state(token1) state2 = await app.state_manager.get_state(token2) - assert state1.var == 1 # type: ignore - assert state2.var == 2 # type: ignore + assert state1.var == 1 + assert state2.var == 2 if isinstance(app.state_manager, StateManagerRedis): await app.state_manager.close() @@ -469,7 +469,7 @@ async def test_dynamic_var_event(test_state: Type[ATestState], token: str): test_state: State Fixture. token: a Token. """ - state = test_state() # type: ignore + state = test_state() # pyright: ignore [reportCallIssue] state.add_var("int_val", int, 0) result = await state._process( Event( @@ -772,7 +772,7 @@ async def test_upload_file(tmp_path, state, delta, token: str, mocker): # The App state must be the "root" of the state tree app = App() app._enable_state() - app.event_namespace.emit = AsyncMock() # type: ignore + app.event_namespace.emit = AsyncMock() # pyright: ignore [reportOptionalMemberAccess] current_state = await app.state_manager.get_state(_substate_key(token, state)) data = b"This is binary data" @@ -795,7 +795,7 @@ async def test_upload_file(tmp_path, state, delta, token: str, mocker): file=bio, ) upload_fn = upload(app) - streaming_response = await upload_fn(request_mock, [file1, file2]) + streaming_response = await upload_fn(request_mock, [file1, file2]) # pyright: ignore [reportFunctionMemberAccess] async for state_update in streaming_response.body_iterator: assert ( state_update @@ -917,7 +917,7 @@ def comp_dynamic(self) -> str: """ return self.dynamic - on_load_internal = OnLoadInternalState.on_load_internal.fn + on_load_internal = OnLoadInternalState.on_load_internal.fn # pyright: ignore [reportFunctionMemberAccess] def test_dynamic_arg_shadow( @@ -941,7 +941,7 @@ def test_dynamic_arg_shadow( app = app_module_mock.app = App(_state=DynamicState) assert app._state is not None with pytest.raises(NameError): - app.add_page(index_page, route=route, on_load=DynamicState.on_load) # type: ignore + app.add_page(index_page, route=route, on_load=DynamicState.on_load) def test_multiple_dynamic_args( @@ -993,7 +993,7 @@ async def test_dynamic_route_var_route_change_completed_on_load( app = app_module_mock.app = App(_state=DynamicState) assert app._state is not None assert arg_name not in app._state.vars - app.add_page(index_page, route=route, on_load=DynamicState.on_load) # type: ignore + app.add_page(index_page, route=route, on_load=DynamicState.on_load) assert arg_name in app._state.vars assert arg_name in app._state.computed_vars assert app._state.computed_vars[arg_name]._deps(objclass=DynamicState) == { @@ -1022,7 +1022,7 @@ def _event(name, val, **kwargs): def _dynamic_state_event(name, val, **kwargs): return _event( - name=format.format_event_handler(getattr(DynamicState, name)), # type: ignore + name=format.format_event_handler(getattr(DynamicState, name)), val=val, **kwargs, ) @@ -1190,7 +1190,7 @@ async def test_process_events(mocker, token: str): pass assert (await app.state_manager.get_state(event.substate_token)).value == 5 - assert app._postprocess.call_count == 6 + assert app._postprocess.call_count == 6 # pyright: ignore [reportFunctionMemberAccess] if isinstance(app.state_manager, StateManagerRedis): await app.state_manager.close() @@ -1226,7 +1226,7 @@ def test_overlay_component( assert app.overlay_component is None elif isinstance(exp_page_child, OverlayFragment): assert app.overlay_component is not None - generated_component = app._generate_component(app.overlay_component) # type: ignore + generated_component = app._generate_component(app.overlay_component) assert isinstance(generated_component, OverlayFragment) assert isinstance( generated_component.children[0], @@ -1235,7 +1235,7 @@ def test_overlay_component( else: assert app.overlay_component is not None assert isinstance( - app._generate_component(app.overlay_component), # type: ignore + app._generate_component(app.overlay_component), exp_page_child, ) @@ -1248,7 +1248,7 @@ def test_overlay_component( if exp_page_child is not None: assert len(page.children) == 3 children_types = (type(child) for child in page.children) - assert exp_page_child in children_types + assert exp_page_child in children_types # pyright: ignore [reportOperatorIssue] else: assert len(page.children) == 2 @@ -1315,19 +1315,19 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]): class Fragment1(Component): tag = "Fragment1" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] return {(99, "Box"): rx.box()} class Fragment2(Component): tag = "Fragment2" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] return {(50, "Text"): rx.text()} class Fragment3(Component): tag = "Fragment3" - def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: + def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride] return {(10, "Fragment2"): Fragment2.create()} def page(): @@ -1448,11 +1448,11 @@ def index_mismatch(): "Bar", ) - comp = App._generate_component(index) # type: ignore + comp = App._generate_component(index) assert isinstance(comp, Component) with pytest.raises(exceptions.MatchTypeError): - App._generate_component(index_mismatch) # type: ignore + App._generate_component(index_mismatch) # pyright: ignore [reportArgumentType] def test_add_page_component_returning_tuple(): @@ -1467,8 +1467,8 @@ def index(): def page2(): return (rx.text("third"),) - app.add_page(index) # type: ignore - app.add_page(page2) # type: ignore + app.add_page(index) # pyright: ignore [reportArgumentType] + app.add_page(page2) # pyright: ignore [reportArgumentType] app._compile_page("index") app._compile_page("page2") @@ -1477,17 +1477,17 @@ def page2(): assert isinstance(fragment_wrapper, Fragment) first_text = fragment_wrapper.children[0] assert isinstance(first_text, Text) - assert str(first_text.children[0].contents) == '"first"' # type: ignore + assert str(first_text.children[0].contents) == '"first"' # pyright: ignore [reportAttributeAccessIssue] second_text = fragment_wrapper.children[1] assert isinstance(second_text, Text) - assert str(second_text.children[0].contents) == '"second"' # type: ignore + assert str(second_text.children[0].contents) == '"second"' # pyright: ignore [reportAttributeAccessIssue] # Test page with trailing comma. page2_fragment_wrapper = app._pages["page2"].children[0] assert isinstance(page2_fragment_wrapper, Fragment) third_text = page2_fragment_wrapper.children[0] assert isinstance(third_text, Text) - assert str(third_text.children[0].contents) == '"third"' # type: ignore + assert str(third_text.children[0].contents) == '"third"' # pyright: ignore [reportAttributeAccessIssue] @pytest.mark.parametrize("export", (True, False)) @@ -1525,7 +1525,7 @@ class C5(rx.Component): next_config = (web_dir / "next.config.js").read_text() transpile_packages_match = re.search(r"transpilePackages: (\[.*?\])", next_config) - transpile_packages_json = transpile_packages_match.group(1) # type: ignore + transpile_packages_json = transpile_packages_match.group(1) # pyright: ignore [reportOptionalMemberAccess] transpile_packages = sorted(json.loads(transpile_packages_json)) assert transpile_packages == [ diff --git a/tests/units/test_config.py b/tests/units/test_config.py index e5d4622bd6c..88d8b5f2f97 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -21,7 +21,7 @@ def test_requires_app_name(): """Test that a config requires an app_name.""" with pytest.raises(ValueError): - rx.Config() # type: ignore + rx.Config() def test_set_app_name(base_config_values): @@ -207,7 +207,7 @@ def test_replace_defaults( exp_config_values: The expected config values. """ mock_os_env = os.environ.copy() - monkeypatch.setattr(reflex.config.os, "environ", mock_os_env) # type: ignore + monkeypatch.setattr(reflex.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) diff --git a/tests/units/test_event.py b/tests/units/test_event.py index 520e876dfca..5e47991da75 100644 --- a/tests/units/test_event.py +++ b/tests/units/test_event.py @@ -72,7 +72,7 @@ def test_fn_with_args(_, arg1, arg2): ) # Passing args as strings should format differently. - event_spec = handler("first", "second") # type: ignore + event_spec = handler("first", "second") assert ( format.format_event(event_spec) == 'Event("test_fn_with_args", {arg1:"first",arg2:"second"})' @@ -80,7 +80,7 @@ def test_fn_with_args(_, arg1, arg2): first, second = 123, "456" handler = EventHandler(fn=test_fn_with_args) - event_spec = handler(first, second) # type: ignore + event_spec = handler(first, second) assert ( format.format_event(event_spec) == 'Event("test_fn_with_args", {arg1:123,arg2:"456"})' @@ -94,7 +94,7 @@ def test_fn_with_args(_, arg1, arg2): handler = EventHandler(fn=test_fn_with_args) with pytest.raises(TypeError): - handler(test_fn) # type: ignore + handler(test_fn) def test_call_event_handler_partial(): @@ -416,7 +416,7 @@ def handler(self): assert isinstance(handler, EventHandler) assert not handler.event_actions - sp_handler = EventActionState.handler.stop_propagation + sp_handler = EventActionState.handler.stop_propagation # pyright: ignore [reportFunctionMemberAccess] assert sp_handler.event_actions == {"stopPropagation": True} # should NOT affect other references to the handler assert not handler.event_actions diff --git a/tests/units/test_health_endpoint.py b/tests/units/test_health_endpoint.py index 6d12d79d6a4..5b3aedc00b2 100644 --- a/tests/units/test_health_endpoint.py +++ b/tests/units/test_health_endpoint.py @@ -122,9 +122,9 @@ async def test_health( # Call the async health function response = await health() - print(json.loads(response.body)) + print(json.loads(response.body)) # pyright: ignore [reportArgumentType] print(expected_status) # Verify the response content and status code assert response.status_code == expected_code - assert json.loads(response.body) == expected_status + assert json.loads(response.body) == expected_status # pyright: ignore [reportArgumentType] diff --git a/tests/units/test_model.py b/tests/units/test_model.py index 0a83f39ec81..b1753824877 100644 --- a/tests/units/test_model.py +++ b/tests/units/test_model.py @@ -86,7 +86,7 @@ def test_automigration( assert versions.exists() # initial table - class AlembicThing(Model, table=True): # type: ignore + class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] t1: str with Model.get_db_engine().connect() as connection: @@ -105,7 +105,7 @@ class AlembicThing(Model, table=True): # type: ignore model_registry.get_metadata().clear() # Create column t2, mark t1 as optional with default - class AlembicThing(Model, table=True): # type: ignore + class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] t1: Optional[str] = "default" t2: str = "bar" @@ -125,7 +125,7 @@ class AlembicThing(Model, table=True): # type: ignore model_registry.get_metadata().clear() # Drop column t1 - class AlembicThing(Model, table=True): # type: ignore + class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] t2: str = "bar" assert Model.migrate(autogenerate=True) @@ -138,7 +138,7 @@ class AlembicThing(Model, table=True): # type: ignore assert result[1].t2 == "baz" # Add table - class AlembicSecond(Model, table=True): # type: ignore + class AlembicSecond(Model, table=True): a: int = 42 b: float = 4.2 @@ -160,14 +160,14 @@ class AlembicSecond(Model, table=True): # type: ignore # drop table (AlembicSecond) model_registry.get_metadata().clear() - class AlembicThing(Model, table=True): # type: ignore + class AlembicThing(Model, table=True): # pyright: ignore [reportRedeclaration] t2: str = "bar" assert Model.migrate(autogenerate=True) assert len(list(versions.glob("*.py"))) == 5 with reflex.model.session() as session: - with pytest.raises(sqlalchemy.exc.OperationalError) as errctx: # type: ignore + with pytest.raises(sqlalchemy.exc.OperationalError) as errctx: session.exec(sqlmodel.select(AlembicSecond)).all() assert errctx.match(r"no such table: alembicsecond") # first table should still exist @@ -178,7 +178,7 @@ class AlembicThing(Model, table=True): # type: ignore model_registry.get_metadata().clear() - class AlembicThing(Model, table=True): # type: ignore + class AlembicThing(Model, table=True): # changing column type not supported by default t2: int = 42 diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index cf655d6cdd0..3bd0290772c 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -100,7 +100,7 @@ def test_transpile_packages(transpile_packages, expected_transpile_packages): transpile_packages=transpile_packages, ) transpile_packages_match = re.search(r"transpilePackages: (\[.*?\])", output) - transpile_packages_json = transpile_packages_match.group(1) # type: ignore + transpile_packages_json = transpile_packages_match.group(1) # pyright: ignore [reportOptionalMemberAccess] actual_transpile_packages = sorted(json.loads(transpile_packages_json)) assert actual_transpile_packages == expected_transpile_packages diff --git a/tests/units/test_sqlalchemy.py b/tests/units/test_sqlalchemy.py index 23e315785a4..4434f5ee12c 100644 --- a/tests/units/test_sqlalchemy.py +++ b/tests/units/test_sqlalchemy.py @@ -59,7 +59,7 @@ class ModelBase(Base, MappedAsDataclass): id: Mapped[Optional[int]] = mapped_column(primary_key=True, default=None) # initial table - class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] + class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] t1: Mapped[str] = mapped_column(default="") with Model.get_db_engine().connect() as connection: @@ -78,7 +78,7 @@ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] model_registry.get_metadata().clear() # Create column t2, mark t1 as optional with default - class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] + class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] t1: Mapped[Optional[str]] = mapped_column(default="default") t2: Mapped[str] = mapped_column(default="bar") @@ -98,7 +98,7 @@ class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] model_registry.get_metadata().clear() # Drop column t1 - class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] + class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] t2: Mapped[str] = mapped_column(default="bar") assert Model.migrate(autogenerate=True) @@ -133,7 +133,7 @@ class AlembicSecond(ModelBase): # drop table (AlembicSecond) model_registry.get_metadata().clear() - class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] + class AlembicThing(ModelBase): # pyright: ignore[reportRedeclaration] t2: Mapped[str] = mapped_column(default="bar") assert Model.migrate(autogenerate=True) diff --git a/tests/units/test_state.py b/tests/units/test_state.py index dfb06862655..b276bad4b81 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -241,7 +241,7 @@ def test_state() -> TestState: Returns: A test state. """ - return TestState() # type: ignore + return TestState() # pyright: ignore [reportCallIssue] @pytest.fixture @@ -431,10 +431,10 @@ def test_default_setters(test_state): def test_class_indexing_with_vars(): """Test that we can index into a state var with another var.""" - prop = TestState.array[TestState.num1] + prop = TestState.array[TestState.num1] # pyright: ignore [reportCallIssue, reportArgumentType] assert str(prop) == f"{TestState.get_name()}.array.at({TestState.get_name()}.num1)" - prop = TestState.mapping["a"][TestState.num1] + prop = TestState.mapping["a"][TestState.num1] # pyright: ignore [reportCallIssue, reportArgumentType] assert ( str(prop) == f'{TestState.get_name()}.mapping["a"].at({TestState.get_name()}.num1)' @@ -554,9 +554,9 @@ def test_get_class_var(): def test_set_class_var(): """Test setting the var of a class.""" with pytest.raises(AttributeError): - TestState.num3 # type: ignore + TestState.num3 # pyright: ignore [reportAttributeAccessIssue] TestState._set_var(Var(_js_expr="num3", _var_type=int)._var_set_state(TestState)) - var = TestState.num3 # type: ignore + var = TestState.num3 # pyright: ignore [reportAttributeAccessIssue] assert var._js_expr == TestState.get_full_name() + ".num3" assert var._var_type is int assert var._var_state == TestState.get_full_name() @@ -848,7 +848,7 @@ async def test_process_event_substate(test_state, child_state, grandchild_state) @pytest.mark.asyncio async def test_process_event_generator(): """Test event handlers that generate multiple updates.""" - gen_state = GenState() # type: ignore + gen_state = GenState() # pyright: ignore [reportCallIssue] event = Event( token="t", name="go", @@ -948,12 +948,12 @@ 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) # type: ignore + assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # pyright: ignore [reportAttributeAccessIssue] # New instances get an actual value with the default assert DynamicState().dynamic_int == 42 ds1.add_var("dynamic_list", List[int], [5, 10]) - assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore + assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # pyright: ignore [reportAttributeAccessIssue] ds2 = DynamicState() assert ds2.dynamic_list == [5, 10] ds2.dynamic_list.append(15) @@ -961,8 +961,8 @@ class DynamicState(BaseState): assert DynamicState().dynamic_list == [5, 10] ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10}) - assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore - assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore + 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} assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10} @@ -1023,7 +1023,7 @@ def v1x2x2(self) -> int: Returns: ComputedVar v1x2 multiplied by 2 """ - return self.v1x2 * 2 # type: ignore + return self.v1x2 * 2 @rx.var def _v3(self) -> int: @@ -1270,7 +1270,7 @@ def no_cache_v(self) -> int: @rx.var def dep_v(self) -> int: - return self.no_cache_v # type: ignore + return self.no_cache_v @rx.var def comp_v(self) -> int: @@ -1313,7 +1313,7 @@ def no_cache_v(self) -> int: class ChildState(ParentState): @rx.var def dep_v(self) -> int: - return self.no_cache_v # type: ignore + return self.no_cache_v ps = ParentState() cs = ps.substates[ChildState.get_name()] @@ -1365,7 +1365,7 @@ def cached_x_side_effect(self) -> int: return counter if use_partial: - HandlerState.handler = functools.partial(HandlerState.handler.fn) + HandlerState.handler = functools.partial(HandlerState.handler.fn) # pyright: ignore [reportFunctionMemberAccess] assert isinstance(HandlerState.handler, functools.partial) else: assert isinstance(HandlerState.handler, EventHandler) @@ -1616,7 +1616,7 @@ def invalid_handler(self): id="backend_error", position="top-center", style={"width": "500px"}, - ) # type: ignore + ) # pyright: ignore [reportCallIssue, reportArgumentType] ], token="", ) @@ -1913,7 +1913,7 @@ def mock_app_simple(monkeypatch) -> rx.App: setattr(app_module, CompileVars.APP, app) app._state = TestState - app.event_namespace.emit = CopyingAsyncMock() # type: ignore + app.event_namespace.emit = CopyingAsyncMock() # pyright: ignore [reportOptionalMemberAccess] def _mock_get_app(*args, **kwargs): return app_module @@ -2022,8 +2022,8 @@ async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App): # ensure state update was emitted assert mock_app.event_namespace is not None - mock_app.event_namespace.emit.assert_called_once() - mcall = mock_app.event_namespace.emit.mock_calls[0] + mock_app.event_namespace.emit.assert_called_once() # pyright: ignore [reportFunctionMemberAccess] + mcall = mock_app.event_namespace.emit.mock_calls[0] # pyright: ignore [reportFunctionMemberAccess] assert mcall.args[0] == str(SocketEvent.EVENT) assert mcall.args[1] == StateUpdate( delta={ @@ -2154,7 +2154,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): """ router_data = {"query": {}} mock_app.state_manager.state = mock_app._state = BackgroundTaskState - async for update in rx.app.process( # type: ignore + async for update in rx.app.process( mock_app, Event( token=token, @@ -2174,7 +2174,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): assert len(mock_app._background_tasks) == 1 # Process another normal event - async for update in rx.app.process( # type: ignore + async for update in rx.app.process( mock_app, Event( token=token, @@ -2224,7 +2224,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): assert mock_app.event_namespace is not None emit_mock = mock_app.event_namespace.emit - first_ws_message = emit_mock.mock_calls[0].args[1] + first_ws_message = emit_mock.mock_calls[0].args[1] # pyright: ignore [reportFunctionMemberAccess] assert ( first_ws_message.delta[BackgroundTaskState.get_full_name()].pop("router") is not None @@ -2239,7 +2239,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): events=[], final=True, ) - for call in emit_mock.mock_calls[1:5]: + for call in emit_mock.mock_calls[1:5]: # pyright: ignore [reportFunctionMemberAccess] assert call.args[1] == StateUpdate( delta={ BackgroundTaskState.get_full_name(): { @@ -2249,7 +2249,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): events=[], final=True, ) - assert emit_mock.mock_calls[-2].args[1] == StateUpdate( + assert emit_mock.mock_calls[-2].args[1] == StateUpdate( # pyright: ignore [reportFunctionMemberAccess] delta={ BackgroundTaskState.get_full_name(): { "order": exp_order, @@ -2260,7 +2260,7 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): events=[], final=True, ) - assert emit_mock.mock_calls[-1].args[1] == StateUpdate( + assert emit_mock.mock_calls[-1].args[1] == StateUpdate( # pyright: ignore [reportFunctionMemberAccess] delta={ BackgroundTaskState.get_full_name(): { "computed_order": exp_order, @@ -2281,7 +2281,7 @@ async def test_background_task_reset(mock_app: rx.App, token: str): """ router_data = {"query": {}} mock_app.state_manager.state = mock_app._state = BackgroundTaskState - async for update in rx.app.process( # type: ignore + async for update in rx.app.process( mock_app, Event( token=token, @@ -2623,10 +2623,10 @@ def test_duplicate_substate_class(mocker): class TestState(BaseState): pass - class ChildTestState(TestState): # type: ignore + class ChildTestState(TestState): # pyright: ignore [reportRedeclaration] pass - class ChildTestState(TestState): # type: ignore # noqa + class ChildTestState(TestState): # noqa: F811 pass return TestState @@ -2664,21 +2664,21 @@ class MutableResetState(BaseState): items: List[List[int]] = default instance = MutableResetState() - assert instance.items.__wrapped__ is not default # type: ignore + assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] 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 # type: ignore + assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] 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 # type: ignore + assert instance.items.__wrapped__ is not default # pyright: ignore [reportAttributeAccessIssue] assert instance.items == default == copied_default instance.items.append([3, 3]) assert instance.items != default @@ -2740,30 +2740,30 @@ class UnionState(BaseState): c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo=""))) custom_union: Union[Custom1, Custom2, Custom3] = Custom1(foo="") - assert str(UnionState.c3.c2) == f'{UnionState.c3!s}?.["c2"]' # type: ignore - assert str(UnionState.c3.c2.c1) == f'{UnionState.c3!s}?.["c2"]?.["c1"]' # type: ignore + 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.c1.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1"]?.["foo"]' # type: ignore + str(UnionState.c3.c2.c1.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1"]?.["foo"]' # pyright: ignore [reportOptionalMemberAccess] ) assert ( - str(UnionState.c3.c2.c1r.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1r"]["foo"]' # type: ignore + str(UnionState.c3.c2.c1r.foo) == f'{UnionState.c3!s}?.["c2"]?.["c1r"]["foo"]' # pyright: ignore [reportOptionalMemberAccess] ) - assert str(UnionState.c3.c2r.c1) == f'{UnionState.c3!s}?.["c2r"]["c1"]' # type: ignore + 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"]' # type: ignore + str(UnionState.c3.c2r.c1.foo) == f'{UnionState.c3!s}?.["c2r"]["c1"]?.["foo"]' # pyright: ignore [reportOptionalMemberAccess] ) assert ( - str(UnionState.c3.c2r.c1r.foo) == f'{UnionState.c3!s}?.["c2r"]["c1r"]["foo"]' # type: ignore + str(UnionState.c3.c2r.c1r.foo) == f'{UnionState.c3!s}?.["c2r"]["c1r"]["foo"]' # pyright: ignore [reportOptionalMemberAccess] ) - assert str(UnionState.c3i.c2) == f'{UnionState.c3i!s}["c2"]' # type: ignore - assert str(UnionState.c3r.c2) == f'{UnionState.c3r!s}["c2"]' # type: ignore - assert UnionState.custom_union.foo is not None # type: ignore - assert UnionState.custom_union.c1 is not None # type: ignore - assert UnionState.custom_union.c1r is not None # type: ignore - assert UnionState.custom_union.c2 is not None # type: ignore - assert UnionState.custom_union.c2r is not None # type: ignore - assert types.is_optional(UnionState.opt_int._var_type) # type: ignore - assert types.is_union(UnionState.int_float._var_type) # type: ignore + 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] def test_set_base_field_via_setter(): @@ -3360,9 +3360,9 @@ def test_redis_state_manager_config_knobs(tmp_path, expiration_kwargs, expected_ from reflex.state import State, StateManager state_manager = StateManager.create(state=State) - assert state_manager.lock_expiration == expected_values[0] # type: ignore - assert state_manager.token_expiration == expected_values[1] # type: ignore - assert state_manager.lock_warning_threshold == expected_values[2] # type: ignore + 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] @pytest.mark.skipif("REDIS_URL" not in os.environ, reason="Test requires redis") @@ -3441,7 +3441,7 @@ def test_mixin_state() -> None: assert "computed" in UsesMixinState.vars assert ( - UsesMixinState(_reflex_internal_init=True)._backend_no_default # type: ignore + UsesMixinState(_reflex_internal_init=True)._backend_no_default # pyright: ignore [reportCallIssue] is not UsesMixinState.backend_vars["_backend_no_default"] ) @@ -3461,7 +3461,7 @@ def test_assignment_to_undeclared_vars(): class State(BaseState): val: str _val: str - __val: str # type: ignore + __val: str # pyright: ignore [reportGeneralTypeIssues] def handle_supported_regular_vars(self): self.val = "no underscore" @@ -3481,8 +3481,8 @@ class Substate(State): def handle_var(self): self.value = 20 - state = State() # type: ignore - sub_state = Substate() # type: ignore + state = State() # pyright: ignore [reportCallIssue] + sub_state = Substate() # pyright: ignore [reportCallIssue] with pytest.raises(SetUndefinedStateVarError): state.handle_regular_var() @@ -3544,7 +3544,7 @@ class DillState(BaseState): _f: Optional[Callable] = None _g: Any = None - state = DillState(_reflex_internal_init=True) # type: ignore + state = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] state._o = Obj(_f=lambda: 42) state._f = lambda: 420 @@ -3555,14 +3555,14 @@ 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) # type: ignore + state2 = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] state2._g = threading.Lock() pk2 = state2._serialize() unpickled_state2 = BaseState._deserialize(pk2) assert isinstance(unpickled_state2._g, type(threading.Lock())) # Some object, like generator, are still unpicklable with dill. - state3 = DillState(_reflex_internal_init=True) # type: ignore + state3 = DillState(_reflex_internal_init=True) # pyright: ignore [reportCallIssue] state3._g = (i for i in range(10)) with pytest.raises(StateSerializationError): @@ -3737,7 +3737,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 # type: ignore + def py_unresolvable(self, u: "Unresolvable"): # noqa: D102, F821 # pyright: ignore [reportUndefinedVariable] assert isinstance(u, list) self.passed = True diff --git a/tests/units/test_style.py b/tests/units/test_style.py index bb585fd2246..6ab00d561db 100644 --- a/tests/units/test_style.py +++ b/tests/units/test_style.py @@ -356,7 +356,7 @@ def test_style_via_component( style_dict: The style_dict to pass to the component. expected_get_style: The expected style dict. """ - comp = rx.el.div(style=style_dict, **kwargs) # type: ignore + comp = rx.el.div(style=style_dict, **kwargs) # pyright: ignore [reportArgumentType] compare_dict_of_var(comp._get_style(), expected_get_style) @@ -515,17 +515,17 @@ def test_evaluate_style_namespaces(): """Test that namespaces get converted to component create functions.""" style_dict = {rx.text: {"color": "blue"}} assert rx.text.__call__ not in style_dict - style_dict = evaluate_style_namespaces(style_dict) # type: ignore + style_dict = evaluate_style_namespaces(style_dict) # pyright: ignore [reportArgumentType] assert rx.text.__call__ in style_dict def test_style_update_with_var_data(): """Test that .update with a Style containing VarData works.""" red_var = LiteralVar.create("red")._replace( - merge_var_data=VarData(hooks={"const red = true": None}), # type: ignore + merge_var_data=VarData(hooks={"const red = true": None}), ) blue_var = LiteralVar.create("blue")._replace( - merge_var_data=VarData(hooks={"const blue = true": None}), # type: ignore + merge_var_data=VarData(hooks={"const blue = true": None}), ) s1 = Style( diff --git a/tests/units/test_var.py b/tests/units/test_var.py index 51b0d9a2b99..899075cdb5f 100644 --- a/tests/units/test_var.py +++ b/tests/units/test_var.py @@ -288,7 +288,7 @@ def test_create(value, expected): expected: The expected name of the setter function. """ prop = LiteralVar.create(value) - assert prop.equals(expected) # type: ignore + assert prop.equals(expected) def test_create_type_error(): @@ -1133,7 +1133,7 @@ def has_eval_react_component(var: Var): for _, imported_objects in var_data.imports ) - has_eval_react_component(ComponentVarState.field_var) # type: ignore + has_eval_react_component(ComponentVarState.field_var) # pyright: ignore [reportArgumentType] has_eval_react_component(ComponentVarState.computed_var) @@ -1145,15 +1145,15 @@ def test_type_chains(): List[int], ) assert ( - str(object_var.keys()[0].upper()) # type: ignore + str(object_var.keys()[0].upper()) == 'Object.keys(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(0).toUpperCase()' ) assert ( - str(object_var.entries()[1][1] - 1) # type: ignore + str(object_var.entries()[1][1] - 1) == '(Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(1).at(1) - 1)' ) assert ( - str(object_var["c"] + object_var["b"]) # type: ignore + str(object_var["c"] + object_var["b"]) # pyright: ignore [reportCallIssue, reportOperatorIssue] == '(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["c"] + ({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["b"])' ) @@ -1162,7 +1162,7 @@ def test_nested_dict(): arr = LiteralArrayVar.create([{"bar": ["foo", "bar"]}], List[Dict[str, List[str]]]) assert ( - str(arr[0]["bar"][0]) == '[({ ["bar"] : ["foo", "bar"] })].at(0)["bar"].at(0)' + str(arr[0]["bar"][0]) == '[({ ["bar"] : ["foo", "bar"] })].at(0)["bar"].at(0)' # pyright: ignore [reportIndexIssue] ) diff --git a/tests/units/utils/test_format.py b/tests/units/utils/test_format.py index 2a2aa8259ff..89197a03ee1 100644 --- a/tests/units/utils/test_format.py +++ b/tests/units/utils/test_format.py @@ -523,7 +523,7 @@ def test_format_event_handler(input, output): input: The event handler input. output: The expected output. """ - assert format.format_event_handler(input) == output # type: ignore + assert format.format_event_handler(input) == output @pytest.mark.parametrize( @@ -582,7 +582,7 @@ def test_format_query_params(input, output): "input, output", [ ( - TestState(_reflex_internal_init=True).dict(), # type: ignore + TestState(_reflex_internal_init=True).dict(), # pyright: ignore [reportCallIssue] { TestState.get_full_name(): { "array": [1, 2, 3.14], @@ -615,7 +615,7 @@ def test_format_query_params(input, output): }, ), ( - DateTimeState(_reflex_internal_init=True).dict(), # type: ignore + DateTimeState(_reflex_internal_init=True).dict(), # pyright: ignore [reportCallIssue] { DateTimeState.get_full_name(): { "d": "1989-11-09", diff --git a/tests/units/utils/test_utils.py b/tests/units/utils/test_utils.py index 65e77f4a77d..44356dac5e2 100644 --- a/tests/units/utils/test_utils.py +++ b/tests/units/utils/test_utils.py @@ -31,7 +31,7 @@ def get_above_max_version(): """ semantic_version_list = constants.Bun.VERSION.split(".") - semantic_version_list[-1] = str(int(semantic_version_list[-1]) + 1) # type: ignore + semantic_version_list[-1] = str(int(semantic_version_list[-1]) + 1) # pyright: ignore [reportArgumentType, reportCallIssue] return ".".join(semantic_version_list) @@ -586,9 +586,7 @@ def test_style_prop_with_event_handler_value(callable): } with pytest.raises(ReflexError): - rx.box( - style=style, # type: ignore - ) + rx.box(style=style) # pyright: ignore [reportArgumentType] def test_is_prod_mode() -> None: