diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index cbc34fff9..6da40ef6f 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -81,15 +81,13 @@ jobs: matrix: # Show OS combos first in GUI os: [ubuntu-latest, windows-latest, macos-latest] - python-version: ["3.9.21", "3.10.16", "3.11.11", "3.12.8"] + python-version: ["3.10.16", "3.11.11", "3.12.8"] exclude: - os: windows-latest python-version: "3.10.16" - os: windows-latest - python-version: "3.9.21" + python-version: "3.11.11" # keep only one python version for MacOS - - os: macos-latest - python-version: "3.9.21" - os: macos-latest python-version: "3.10.16" - os: macos-latest @@ -98,7 +96,7 @@ jobs: - os: windows-latest python-version: "3.10.11" - os: windows-latest - python-version: "3.9.13" + python-version: "3.11.9" runs-on: ${{ matrix.os }} steps: @@ -161,7 +159,11 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - + - name: Set up python + id: setup-python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} - name: Install Poetry uses: snok/install-poetry@v1 with: diff --git a/.github/workflows/check_outdated_dependencies.yml b/.github/workflows/check_outdated_dependencies.yml index 30e048912..34bfa23bf 100644 --- a/.github/workflows/check_outdated_dependencies.yml +++ b/.github/workflows/check_outdated_dependencies.yml @@ -16,7 +16,7 @@ jobs: - uses: ./.github/actions/setup_build_env with: - python-version: "3.9.21" + python-version: '3.10' run-poetry-install: true create-venv-at-path: .venv @@ -55,7 +55,7 @@ jobs: path: reflex-web - name: Install Requirements for reflex-web working-directory: ./reflex-web - run: poetry run uv pip install -r requirements.txt + run: poetry run uv pip install $(grep -ivE "reflex " requirements.txt) - name: Install additional dependencies for DB access run: poetry run uv pip install psycopg - name: Init Website for reflex-web @@ -73,7 +73,7 @@ jobs: echo "$outdated" # Ignore 3rd party dependencies that are not updated. - filtered_outdated=$(echo "$outdated" | grep -vE 'Package|@chakra-ui|lucide-react|@splinetool/runtime|ag-grid-react|framer-motion|react-markdown|remark-math|remark-gfm|rehype-katex|rehype-raw|remark-unwrap-images' || true) + filtered_outdated=$(echo "$outdated" | grep -vE 'Package|@chakra-ui|lucide-react|@splinetool/runtime|ag-grid-react|framer-motion|react-markdown|remark-math|remark-gfm|rehype-katex|rehype-raw|remark-unwrap-images|ag-grid' || true) no_extra=$(echo "$filtered_outdated" | grep -vE '\|\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-' || true) diff --git a/.github/workflows/integration_app_harness.yml b/.github/workflows/integration_app_harness.yml index 6148ecd1a..0bafd3601 100644 --- a/.github/workflows/integration_app_harness.yml +++ b/.github/workflows/integration_app_harness.yml @@ -47,17 +47,10 @@ jobs: python-version: ${{ matrix.python-version }} run-poetry-install: true create-venv-at-path: .venv - - run: poetry run uv pip install pyvirtualdisplay pillow pytest-split + - run: poetry run uv pip install pyvirtualdisplay pillow pytest-split pytest-retry - name: Run app harness tests env: - SCREENSHOT_DIR: /tmp/screenshots/${{ matrix.state_manager }}/${{ matrix.python-version }}/${{ matrix.split_index }} REDIS_URL: ${{ matrix.state_manager == 'redis' && 'redis://localhost:6379' || '' }} run: | poetry run playwright install chromium - poetry run pytest tests/integration --splits 2 --group ${{matrix.split_index}} - - uses: actions/upload-artifact@v4 - name: Upload failed test screenshots - if: always() - with: - name: failed_test_screenshots - path: /tmp/screenshots + poetry run pytest tests/integration --retries 3 --maxfail=5 --splits 2 --group ${{matrix.split_index}} diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml index 017336ba5..b02604fd6 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -33,7 +33,7 @@ env: PR_TITLE: ${{ github.event.pull_request.title }} jobs: - example-counter: + example-counter-and-nba-proxy: env: OUTPUT_FILE: import_benchmark.json timeout-minutes: 30 @@ -43,22 +43,17 @@ jobs: matrix: # Show OS combos first in GUI os: [ubuntu-latest, windows-latest] - python-version: ["3.9.21", "3.10.16", "3.11.11", "3.12.8", "3.13.1"] - # Windows is a bit behind on Python version availability in Github + python-version: ['3.10.16', '3.11.11', '3.12.8', '3.13.1'] exclude: - os: windows-latest python-version: "3.11.11" - os: windows-latest - python-version: "3.10.16" - - os: windows-latest - python-version: "3.9.21" + python-version: '3.10.16' include: - os: windows-latest python-version: "3.11.9" - os: windows-latest - python-version: "3.10.11" - - os: windows-latest - python-version: "3.9.13" + python-version: '3.10.11' runs-on: ${{ matrix.os }} steps: @@ -119,6 +114,26 @@ jobs: --benchmark-json "./reflex-examples/counter/${{ env.OUTPUT_FILE }}" --branch-name "${{ github.head_ref || github.ref_name }}" --pr-id "${{ github.event.pull_request.id }}" --app-name "counter" + - name: Install requirements for nba proxy example + working-directory: ./reflex-examples/nba-proxy + run: | + poetry run uv pip install -r requirements.txt + - name: Install additional dependencies for DB access + run: poetry run uv pip install psycopg + - name: Check export --backend-only before init for nba-proxy example + working-directory: ./reflex-examples/nba-proxy + run: | + poetry run reflex export --backend-only + - name: Init Website for nba-proxy example + working-directory: ./reflex-examples/nba-proxy + run: | + poetry run reflex init --loglevel debug + - name: Run Website and Check for errors + run: | + # Check that npm is home + npm -v + poetry run bash scripts/integration.sh ./reflex-examples/nba-proxy dev + reflex-web: strategy: diff --git a/.github/workflows/performance.yml b/.github/workflows/performance.yml new file mode 100644 index 000000000..c7bd1003a --- /dev/null +++ b/.github/workflows/performance.yml @@ -0,0 +1,34 @@ +name: performance-tests + +on: + push: + branches: + - "main" # or "master" + paths-ignore: + - "**/*.md" + pull_request: + workflow_dispatch: + +env: + TELEMETRY_ENABLED: false + NODE_OPTIONS: "--max_old_space_size=8192" + PR_TITLE: ${{ github.event.pull_request.title }} + APP_HARNESS_HEADLESS: 1 + PYTHONUNBUFFERED: 1 + +jobs: + benchmarks: + name: Run benchmarks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/setup_build_env + with: + python-version: 3.12.8 + run-poetry-install: true + create-venv-at-path: .venv + - name: Run benchmarks + uses: CodSpeedHQ/action@v3 + with: + token: ${{ secrets.CODSPEED_TOKEN }} + run: poetry run pytest benchmarks/test_evaluate.py --codspeed diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index e0a3723ac..1ef063ca7 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -28,22 +28,18 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] - python-version: ["3.9.21", "3.10.16", "3.11.11", "3.12.8", "3.13.1"] + python-version: ["3.10.16", "3.11.11", "3.12.8", "3.13.1"] # Windows is a bit behind on Python version availability in Github exclude: - os: windows-latest python-version: "3.11.11" - os: windows-latest python-version: "3.10.16" - - os: windows-latest - python-version: "3.9.21" include: - os: windows-latest python-version: "3.11.9" - os: windows-latest python-version: "3.10.11" - - os: windows-latest - python-version: "3.9.13" runs-on: ${{ matrix.os }} # Service containers to run with `runner-job` @@ -92,8 +88,8 @@ jobs: strategy: fail-fast: false matrix: - # Note: py39, py310, py311 versions chosen due to available arm64 darwin builds. - python-version: ["3.9.13", "3.10.11", "3.11.9", "3.12.8", "3.13.1"] + # Note: py310, py311 versions chosen due to available arm64 darwin builds. + python-version: ["3.10.11", "3.11.9", "3.12.8", "3.13.1"] runs-on: macos-latest steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index 0f7d9e5ff..29a868796 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ assets/external/* dist/* examples/ .web +.states .idea .vscode .coverage @@ -14,3 +15,4 @@ requirements.txt .pyi_generator_last_run .pyi_generator_diff reflex.db +.codspeed \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ac25a335e..0bad7b996 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ fail_fast: true repos: - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.8.2 + rev: v0.9.3 hooks: - id: ruff-format args: [reflex, tests] @@ -24,11 +24,12 @@ repos: name: update-pyi-files always_run: true language: system + require_serial: true description: 'Update pyi files as needed' entry: python3 scripts/make_pyi.py - repo: https://github.com/RobertCraigie/pyright-python - rev: v1.1.313 + rev: v1.1.393 hooks: - id: pyright args: [reflex, tests] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc8398013..aed576c42 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,7 @@ Here is a quick guide on how to run Reflex repo locally so you can start contrib **Prerequisites:** -- Python >= 3.9 +- Python >= 3.10 - Poetry version >= 1.4.0 and add it to your path (see [Poetry Docs](https://python-poetry.org/docs/#installation) for more info). **1. Fork this repository:** @@ -87,7 +87,7 @@ poetry run ruff format . ``` Consider installing git pre-commit hooks so Ruff, Pyright, Darglint and `make_pyi` will run automatically before each commit. -Note that pre-commit will only be installed when you use a Python version >= 3.9. +Note that pre-commit will only be installed when you use a Python version >= 3.10. ``` bash pre-commit install diff --git a/README.md b/README.md index 5e098b2d3..5174d563e 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ See our [architecture page](https://reflex.dev/blog/2024-03-21-reflex-architectu ## ⚙️ Installation -Open a terminal and run (Requires Python 3.9+): +Open a terminal and run (Requires Python 3.10+): ```bash pip install reflex diff --git a/benchmarks/benchmark_package_size.py b/benchmarks/benchmark_package_size.py index 6a0c37821..778b52769 100644 --- a/benchmarks/benchmark_package_size.py +++ b/benchmarks/benchmark_package_size.py @@ -21,7 +21,7 @@ def get_package_size(venv_path: Path, os_name): ValueError: when venv does not exist or python version is None. """ python_version = get_python_version(venv_path, os_name) - print("Python version:", python_version) # noqa: T201 + print("Python version:", python_version) if python_version is None: raise ValueError("Error: Failed to determine Python version.") diff --git a/benchmarks/test_benchmark_compile_components.py b/benchmarks/test_benchmark_compile_components.py index 81d0c2e89..9bcfbf85b 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", @@ -122,7 +122,7 @@ def AppWithTenComponentsOnePage(): def index() -> rx.Component: return rx.center(rx.vstack(*render_component(1))) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) @@ -133,7 +133,7 @@ def AppWithHundredComponentOnePage(): def index() -> rx.Component: return rx.center(rx.vstack(*render_component(100))) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) @@ -144,7 +144,7 @@ def AppWithThousandComponentsOnePage(): def index() -> rx.Component: return rx.center(rx.vstack(*render_component(1000))) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) @@ -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 292882b74..149fc6130 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 @@ def render_multiple_pages(app, num: int): 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 @@ def render_multiple_pages(app, num: int): 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 @@ def render_multiple_pages(app, num: int): 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 @@ def render_multiple_pages(app, num: int): 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 @@ -162,7 +162,7 @@ def AppWithOnePage(): height="100vh", ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) @@ -170,7 +170,7 @@ def AppWithTenPages(): """A reflex app with 10 pages.""" import reflex as rx - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) render_multiple_pages(app, 10) @@ -178,7 +178,7 @@ def AppWithHundredPages(): """A reflex app with 100 pages.""" import reflex as rx - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) render_multiple_pages(app, 100) @@ -186,7 +186,7 @@ def AppWithThousandPages(): """A reflex app with Thousand pages.""" import reflex as rx - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) render_multiple_pages(app, 1000) @@ -194,7 +194,7 @@ def AppWithTenThousandPages(): """A reflex app with ten thousand pages.""" import reflex as rx - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) render_multiple_pages(app, 10000) @@ -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/benchmarks/test_evaluate.py b/benchmarks/test_evaluate.py new file mode 100644 index 000000000..aa4c8237e --- /dev/null +++ b/benchmarks/test_evaluate.py @@ -0,0 +1,231 @@ +from dataclasses import dataclass +from typing import cast + +import pytest + +import reflex as rx + + +class SideBarState(rx.State): + """State for the side bar.""" + + current_page: rx.Field[str] = rx.field("/") + + +@dataclass(frozen=True) +class SideBarPage: + """A page in the side bar.""" + + title: str + href: str + + +@dataclass(frozen=True) +class SideBarSection: + """A section in the side bar.""" + + name: str + icon: str + pages: tuple[SideBarPage, ...] + + +@dataclass(frozen=True) +class Category: + """A category in the side bar.""" + + name: str + href: str + sections: tuple[SideBarSection, ...] + + +SIDE_BAR = ( + Category( + name="General", + href="/", + sections=( + SideBarSection( + name="Home", + icon="home", + pages=( + SideBarPage(title="Home", href="/"), + SideBarPage(title="Contact", href="/contact"), + ), + ), + SideBarSection( + name="About", + icon="info", + pages=( + SideBarPage(title="About", href="/about"), + SideBarPage(title="FAQ", href="/faq"), + ), + ), + ), + ), + Category( + name="Projects", + href="/projects", + sections=( + SideBarSection( + name="Python", + icon="worm", + pages=( + SideBarPage(title="Python", href="/projects/python"), + SideBarPage(title="Django", href="/projects/django"), + SideBarPage(title="Flask", href="/projects/flask"), + SideBarPage(title="FastAPI", href="/projects/fastapi"), + SideBarPage(title="Pyramid", href="/projects/pyramid"), + SideBarPage(title="Tornado", href="/projects/tornado"), + SideBarPage(title="TurboGears", href="/projects/turbogears"), + SideBarPage(title="Web2py", href="/projects/web2py"), + SideBarPage(title="Zope", href="/projects/zope"), + SideBarPage(title="Plone", href="/projects/plone"), + SideBarPage(title="Quixote", href="/projects/quixote"), + SideBarPage(title="Bottle", href="/projects/bottle"), + SideBarPage(title="CherryPy", href="/projects/cherrypy"), + SideBarPage(title="Falcon", href="/projects/falcon"), + SideBarPage(title="Sanic", href="/projects/sanic"), + SideBarPage(title="Starlette", href="/projects/starlette"), + ), + ), + SideBarSection( + name="JavaScript", + icon="banana", + pages=( + SideBarPage(title="JavaScript", href="/projects/javascript"), + SideBarPage(title="Angular", href="/projects/angular"), + SideBarPage(title="React", href="/projects/react"), + SideBarPage(title="Vue", href="/projects/vue"), + SideBarPage(title="Ember", href="/projects/ember"), + SideBarPage(title="Backbone", href="/projects/backbone"), + SideBarPage(title="Meteor", href="/projects/meteor"), + SideBarPage(title="Svelte", href="/projects/svelte"), + SideBarPage(title="Preact", href="/projects/preact"), + SideBarPage(title="Mithril", href="/projects/mithril"), + SideBarPage(title="Aurelia", href="/projects/aurelia"), + SideBarPage(title="Polymer", href="/projects/polymer"), + SideBarPage(title="Knockout", href="/projects/knockout"), + SideBarPage(title="Dojo", href="/projects/dojo"), + SideBarPage(title="Riot", href="/projects/riot"), + SideBarPage(title="Alpine", href="/projects/alpine"), + SideBarPage(title="Stimulus", href="/projects/stimulus"), + SideBarPage(title="Marko", href="/projects/marko"), + SideBarPage(title="Sapper", href="/projects/sapper"), + SideBarPage(title="Nuxt", href="/projects/nuxt"), + SideBarPage(title="Next", href="/projects/next"), + SideBarPage(title="Gatsby", href="/projects/gatsby"), + SideBarPage(title="Gridsome", href="/projects/gridsome"), + SideBarPage(title="Nest", href="/projects/nest"), + SideBarPage(title="Express", href="/projects/express"), + SideBarPage(title="Koa", href="/projects/koa"), + SideBarPage(title="Hapi", href="/projects/hapi"), + SideBarPage(title="LoopBack", href="/projects/loopback"), + SideBarPage(title="Feathers", href="/projects/feathers"), + SideBarPage(title="Sails", href="/projects/sails"), + SideBarPage(title="Adonis", href="/projects/adonis"), + SideBarPage(title="Meteor", href="/projects/meteor"), + SideBarPage(title="Derby", href="/projects/derby"), + SideBarPage(title="Socket.IO", href="/projects/socketio"), + ), + ), + ), + ), +) + + +def side_bar_page(page: SideBarPage): + return rx.box( + rx.link( + page.title, + href=page.href, + ) + ) + + +def side_bar_section(section: SideBarSection): + return rx.accordion.item( + rx.accordion.header( + rx.accordion.trigger( + rx.hstack( + rx.hstack( + rx.icon(section.icon), + section.name, + align="center", + ), + rx.accordion.icon(), + width="100%", + justify="between", + ) + ) + ), + rx.accordion.content( + rx.vstack( + *map(side_bar_page, section.pages), + ), + border_inline_start="1px solid", + padding_inline_start="1em", + margin_inline_start="1.5em", + ), + value=section.name, + width="100%", + variant="ghost", + ) + + +def side_bar_category(category: Category): + selected_section = cast( + rx.Var, + rx.match( + SideBarState.current_page, + *[ + ( + section.name, + section.name, + ) + for section in category.sections + ], + None, + ), + ) + return rx.vstack( + rx.heading( + rx.link( + category.name, + href=category.href, + ), + size="5", + ), + rx.accordion.root( + *map(side_bar_section, category.sections), + default_value=selected_section.to(str), + variant="ghost", + width="100%", + collapsible=True, + type="multiple", + ), + width="100%", + ) + + +def side_bar(): + return rx.vstack( + *map(side_bar_category, SIDE_BAR), + width="fit-content", + ) + + +LOREM_IPSUM = "Lorem ipsum dolor sit amet, dolor ut dolore pariatur aliqua enim tempor sed. Labore excepteur sed exercitation. Ullamco aliquip lorem sunt enim in incididunt. Magna anim officia sint cillum labore. Ut eu non dolore minim nostrud magna eu, aute ex in incididunt irure eu. Fugiat et magna magna est excepteur eiusmod minim. Quis eiusmod et non pariatur dolor veniam incididunt, eiusmod irure enim sed dolor lorem pariatur do. Occaecat duis irure excepteur dolore. Proident ut laborum pariatur sit sit, nisi nostrud voluptate magna commodo laborum esse velit. Voluptate non minim deserunt adipiscing irure deserunt cupidatat. Laboris veniam commodo incididunt veniam lorem occaecat, fugiat ipsum dolor cupidatat. Ea officia sed eu excepteur culpa adipiscing, tempor consectetur ullamco eu. Anim ex proident nulla sunt culpa, voluptate veniam proident est adipiscing sint elit velit. Laboris adipiscing est culpa cillum magna. Sit veniam nulla nulla, aliqua eiusmod commodo lorem cupidatat commodo occaecat. Fugiat cillum dolor incididunt mollit eiusmod sint. Non lorem dolore labore excepteur minim laborum sed. Irure nisi do lorem nulla sunt commodo, deserunt quis mollit consectetur minim et esse est, proident nostrud officia enim sed reprehenderit. Magna cillum consequat aute reprehenderit duis sunt ullamco. Labore qui mollit voluptate. Duis dolor sint aute amet aliquip officia, est non mollit tempor enim quis fugiat, eu do culpa consectetur magna. Do ullamco aliqua voluptate culpa excepteur reprehenderit reprehenderit. Occaecat nulla sit est magna. Deserunt ea voluptate veniam cillum. Amet cupidatat duis est tempor fugiat ex eu, officia est sunt consectetur labore esse exercitation. Nisi cupidatat irure est nisi. Officia amet eu veniam reprehenderit. In amet incididunt tempor commodo ea labore. Mollit dolor aliquip excepteur, voluptate aute occaecat id officia proident. Ullamco est amet tempor. Proident aliquip proident mollit do aliquip ipsum, culpa quis aute id irure. Velit excepteur cillum cillum ut cupidatat. Occaecat qui elit esse nulla minim. Consequat velit id ad pariatur tempor. Eiusmod deserunt aliqua ex sed quis non. Dolor sint commodo ex in deserunt nostrud excepteur, pariatur ex aliqua anim adipiscing amet proident. Laboris eu laborum magna lorem ipsum fugiat velit." + + +def complicated_page(): + return rx.hstack( + side_bar(), + rx.box( + rx.heading("Complicated Page", size="1"), + rx.text(LOREM_IPSUM), + ), + ) + + +@pytest.mark.benchmark +def test_component_init(): + complicated_page() diff --git a/docs/de/README.md b/docs/de/README.md index 9931c24cc..6d2d69e94 100644 --- a/docs/de/README.md +++ b/docs/de/README.md @@ -34,7 +34,7 @@ Auf unserer [Architektur-Seite](https://reflex.dev/blog/2024-03-21-reflex-archit ## ⚙️ Installation -Öffne ein Terminal und führe den folgenden Befehl aus (benötigt Python 3.9+): +Öffne ein Terminal und führe den folgenden Befehl aus (benötigt Python 3.10+): ```bash pip install reflex diff --git a/docs/es/README.md b/docs/es/README.md index 15ce63335..538192e4b 100644 --- a/docs/es/README.md +++ b/docs/es/README.md @@ -35,7 +35,7 @@ Consulta nuestra [página de arquitectura](https://reflex.dev/blog/2024-03-21-re ## ⚙️ Instalación -Abra un terminal y ejecute (Requiere Python 3.9+): +Abra un terminal y ejecute (Requiere Python 3.10+): ```bash pip install reflex diff --git a/docs/in/README.md b/docs/in/README.md index ebc4155f4..81b1106ff 100644 --- a/docs/in/README.md +++ b/docs/in/README.md @@ -35,7 +35,7 @@ Reflex के अंदर के कामकाज को जानने क ## ⚙️ इंस्टॉलेशन (Installation) -एक टर्मिनल खोलें और चलाएं (Python 3.9+ की आवश्यकता है): +एक टर्मिनल खोलें और चलाएं (Python 3.10+ की आवश्यकता है): ```bash pip install reflex diff --git a/docs/it/README.md b/docs/it/README.md index 92438f696..cd6f24dd8 100644 --- a/docs/it/README.md +++ b/docs/it/README.md @@ -22,7 +22,7 @@ ## ⚙️ Installazione -Apri un terminale ed esegui (Richiede Python 3.9+): +Apri un terminale ed esegui (Richiede Python 3.10+): ```bash pip install reflex diff --git a/docs/ja/README.md b/docs/ja/README.md index 0a7ab0d53..941bef601 100644 --- a/docs/ja/README.md +++ b/docs/ja/README.md @@ -37,7 +37,7 @@ Reflex がどのように動作しているかを知るには、[アーキテク ## ⚙️ インストール -ターミナルを開いて以下のコマンドを実行してください。(Python 3.9 以上が必要です。): +ターミナルを開いて以下のコマンドを実行してください。(Python 3.10 以上が必要です。): ```bash pip install reflex diff --git a/docs/kr/README.md b/docs/kr/README.md index a92fcd0c5..57bb43794 100644 --- a/docs/kr/README.md +++ b/docs/kr/README.md @@ -20,7 +20,7 @@ --- ## ⚙️ 설치 -터미널을 열고 실행하세요. (Python 3.9+ 필요): +터미널을 열고 실행하세요. (Python 3.10+ 필요): ```bash pip install reflex diff --git a/docs/pe/README.md b/docs/pe/README.md index 3a0ba044b..867b543bc 100644 --- a/docs/pe/README.md +++ b/docs/pe/README.md @@ -34,7 +34,7 @@ ## ⚙️ Installation - نصب و راه اندازی -یک ترمینال را باز کنید و اجرا کنید (نیازمند Python 3.9+): +یک ترمینال را باز کنید و اجرا کنید (نیازمند Python 3.10+): ```bash pip install reflex diff --git a/docs/pt/pt_br/README.md b/docs/pt/pt_br/README.md index 184b668bc..8abfaebde 100644 --- a/docs/pt/pt_br/README.md +++ b/docs/pt/pt_br/README.md @@ -21,7 +21,7 @@ --- ## ⚙️ Instalação -Abra um terminal e execute (Requer Python 3.9+): +Abra um terminal e execute (Requer Python 3.10+): ```bash pip install reflex diff --git a/docs/tr/README.md b/docs/tr/README.md index 376547e01..afb8ae5b9 100644 --- a/docs/tr/README.md +++ b/docs/tr/README.md @@ -24,7 +24,7 @@ ## ⚙️ Kurulum -Bir terminal açın ve çalıştırın (Python 3.9+ gerekir): +Bir terminal açın ve çalıştırın (Python 3.10+ gerekir): ```bash pip install reflex diff --git a/docs/vi/README.md b/docs/vi/README.md index df7a31530..53fcad936 100644 --- a/docs/vi/README.md +++ b/docs/vi/README.md @@ -34,7 +34,7 @@ Các tính năng chính: ## ⚙️ Cài đặt -Mở cửa sổ lệnh và chạy (Yêu cầu Python phiên bản 3.9+): +Mở cửa sổ lệnh và chạy (Yêu cầu Python phiên bản 3.10+): ```bash pip install reflex diff --git a/docs/zh/zh_cn/README.md b/docs/zh/zh_cn/README.md index e114bc1e2..efaec0ca5 100644 --- a/docs/zh/zh_cn/README.md +++ b/docs/zh/zh_cn/README.md @@ -34,7 +34,7 @@ Reflex 是一个使用纯Python构建全栈web应用的库。 ## ⚙️ 安装 -打开一个终端并且运行(要求Python3.9+): +打开一个终端并且运行(要求Python3.10+): ```bash pip install reflex diff --git a/docs/zh/zh_tw/README.md b/docs/zh/zh_tw/README.md index 83f6b2ae2..6161e17d0 100644 --- a/docs/zh/zh_tw/README.md +++ b/docs/zh/zh_tw/README.md @@ -36,7 +36,7 @@ Reflex 是一個可以用純 Python 構建全端網頁應用程式的函式庫 ## ⚙️ 安裝 -開啟一個終端機並且執行 (需要 Python 3.9+): +開啟一個終端機並且執行 (需要 Python 3.10+): ```bash pip install reflex diff --git a/poetry.lock b/poetry.lock index f32a5a2e0..f5007ee07 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 1.8.3 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" @@ -6,6 +6,8 @@ version = "1.14.1" description = "A database migration tool for SQLAlchemy." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "alembic-1.14.1-py3-none-any.whl", hash = "sha256:1acdd7a3a478e208b0503cd73614d5e4c6efafa4e73518bb60e4f2846a37b1c5"}, {file = "alembic-1.14.1.tar.gz", hash = "sha256:496e888245a53adf1498fcab31713a469c65836f8de76e01399aa1c3e90dd213"}, @@ -25,6 +27,8 @@ version = "0.7.0" description = "Reusable constraint types to use with typing.Annotated" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53"}, {file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"}, @@ -36,6 +40,8 @@ version = "4.8.0" description = "High level compatibility layer for multiple asynchronous event loop implementations" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "anyio-4.8.0-py3-none-any.whl", hash = "sha256:b5011f270ab5eb0abf13385f851315585cc37ef330dd88e27ec3d34d651fd47a"}, {file = "anyio-4.8.0.tar.gz", hash = "sha256:1d9fe889df5212298c0c0723fa20479d1b94883a2df44bd3897aa91083316f7a"}, @@ -58,6 +64,8 @@ version = "5.0.1" description = "Timeout context manager for asyncio programs" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_full_version < \"3.11.3\"" files = [ {file = "async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c"}, {file = "async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3"}, @@ -69,6 +77,8 @@ version = "0.13.0" description = "Enhance the standard unittest package with features for testing asyncio libraries" optional = false python-versions = ">=3.5" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "asynctest-0.13.0-py3-none-any.whl", hash = "sha256:5da6118a7e6d6b54d83a8f7197769d046922a44d2a99c21382f0a6e4fadae676"}, {file = "asynctest-0.13.0.tar.gz", hash = "sha256:c27862842d15d83e6a34eb0b2866c323880eb3a75e4485b079ea11748fd77fac"}, @@ -76,13 +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] @@ -99,6 +111,8 @@ version = "1.2.0" description = "Backport of CPython tarfile module" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and python_version <= \"3.11\"" files = [ {file = "backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34"}, {file = "backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991"}, @@ -114,6 +128,8 @@ version = "0.23.1" description = "The bidirectional mapping library for Python." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "bidict-0.23.1-py3-none-any.whl", hash = "sha256:5dae8d4d79b552a71cbabc7deb25dfe8ce710b17ff41711e13010ead2abfc3e5"}, {file = "bidict-0.23.1.tar.gz", hash = "sha256:03069d763bc387bbd20e7d49914e75fc4132a41937fa3405417e1a5a2d006d71"}, @@ -125,6 +141,8 @@ version = "1.2.2.post1" description = "A simple, correct Python build frontend" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "build-1.2.2.post1-py3-none-any.whl", hash = "sha256:1d61c0887fa860c01971625baae8bdd338e517b836a2f70dd1f7aa3a6b2fc5b5"}, {file = "build-1.2.2.post1.tar.gz", hash = "sha256:b36993e92ca9375a219c99e606a122ff365a760a2d4bba0caa09bd5278b608b7"}, @@ -146,13 +164,15 @@ virtualenv = ["virtualenv (>=20.0.35)"] [[package]] name = "certifi" -version = "2024.12.14" +version = "2025.1.31" description = "Python package for providing Mozilla's CA Bundle." optional = false python-versions = ">=3.6" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "certifi-2024.12.14-py3-none-any.whl", hash = "sha256:1275f7a45be9464efc1173084eaa30f866fe2e47d389406136d332ed4967ec56"}, - {file = "certifi-2024.12.14.tar.gz", hash = "sha256:b650d30f370c2b724812bee08008be0c4163b163ddaec3f2546c1caf65f191db"}, + {file = "certifi-2025.1.31-py3-none-any.whl", hash = "sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe"}, + {file = "certifi-2025.1.31.tar.gz", hash = "sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651"}, ] [[package]] @@ -161,6 +181,7 @@ version = "1.17.1" description = "Foreign Function Interface for Python calling C code." optional = false python-versions = ">=3.8" +groups = ["main", "dev"] files = [ {file = "cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14"}, {file = "cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67"}, @@ -230,6 +251,7 @@ files = [ {file = "cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662"}, {file = "cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824"}, ] +markers = {main = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"linux\" and platform_python_implementation != \"PyPy\" and (python_version <= \"3.11\" or python_version >= \"3.12\")", dev = "python_version <= \"3.11\" or python_version >= \"3.12\""} [package.dependencies] pycparser = "*" @@ -240,6 +262,8 @@ version = "3.4.0" description = "Validate configuration and produce human readable error messages." optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9"}, {file = "cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560"}, @@ -251,6 +275,8 @@ version = "3.4.1" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." optional = false python-versions = ">=3.7" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "charset_normalizer-3.4.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:91b36a978b5ae0ee86c394f5a54d6ef44db1de0815eb43de826d41d21e4af3de"}, {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7461baadb4dc00fd9e0acbe254e3d7d2112e7f92ced2adc96e54ef6501c5f176"}, @@ -352,6 +378,8 @@ version = "8.1.8" description = "Composable command line interface toolkit" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"}, {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"}, @@ -366,10 +394,12 @@ version = "0.4.6" description = "Cross-platform colored terminal text." optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["main", "dev"] files = [ {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, ] +markers = {main = "(platform_system == \"Windows\" or os_name == \"nt\") and (python_version <= \"3.11\" or python_version >= \"3.12\")", dev = "(python_version <= \"3.11\" or python_version >= \"3.12\") and sys_platform == \"win32\""} [[package]] name = "coverage" @@ -377,6 +407,8 @@ version = "7.6.10" description = "Code coverage measurement for Python" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "coverage-7.6.10-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5c912978f7fbf47ef99cec50c4401340436d200d41d714c7a4766f377c5b7b78"}, {file = "coverage-7.6.10-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a01ec4af7dfeb96ff0078ad9a48810bb0cc8abcb0115180c6013a6b26237626c"}, @@ -450,51 +482,53 @@ toml = ["tomli"] [[package]] name = "cryptography" -version = "43.0.3" +version = "44.0.0" description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." optional = false -python-versions = ">=3.7" +python-versions = "!=3.9.0,!=3.9.1,>=3.7" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"linux\" and (python_version <= \"3.11\" or python_version >= \"3.12\")" files = [ - {file = "cryptography-43.0.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:bf7a1932ac4176486eab36a19ed4c0492da5d97123f1406cf15e41b05e787d2e"}, - {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63efa177ff54aec6e1c0aefaa1a241232dcd37413835a9b674b6e3f0ae2bfd3e"}, - {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e1ce50266f4f70bf41a2c6dc4358afadae90e2a1e5342d3c08883df1675374f"}, - {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:443c4a81bb10daed9a8f334365fe52542771f25aedaf889fd323a853ce7377d6"}, - {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:74f57f24754fe349223792466a709f8e0c093205ff0dca557af51072ff47ab18"}, - {file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9762ea51a8fc2a88b70cf2995e5675b38d93bf36bd67d91721c309df184f49bd"}, - {file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:81ef806b1fef6b06dcebad789f988d3b37ccaee225695cf3e07648eee0fc6b73"}, - {file = "cryptography-43.0.3-cp37-abi3-win32.whl", hash = "sha256:cbeb489927bd7af4aa98d4b261af9a5bc025bd87f0e3547e11584be9e9427be2"}, - {file = "cryptography-43.0.3-cp37-abi3-win_amd64.whl", hash = "sha256:f46304d6f0c6ab8e52770addfa2fc41e6629495548862279641972b6215451cd"}, - {file = "cryptography-43.0.3-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:8ac43ae87929a5982f5948ceda07001ee5e83227fd69cf55b109144938d96984"}, - {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:846da004a5804145a5f441b8530b4bf35afbf7da70f82409f151695b127213d5"}, - {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f996e7268af62598f2fc1204afa98a3b5712313a55c4c9d434aef49cadc91d4"}, - {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f7b178f11ed3664fd0e995a47ed2b5ff0a12d893e41dd0494f406d1cf555cab7"}, - {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c2e6fc39c4ab499049df3bdf567f768a723a5e8464816e8f009f121a5a9f4405"}, - {file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e1be4655c7ef6e1bbe6b5d0403526601323420bcf414598955968c9ef3eb7d16"}, - {file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:df6b6c6d742395dd77a23ea3728ab62f98379eff8fb61be2744d4679ab678f73"}, - {file = "cryptography-43.0.3-cp39-abi3-win32.whl", hash = "sha256:d56e96520b1020449bbace2b78b603442e7e378a9b3bd68de65c782db1507995"}, - {file = "cryptography-43.0.3-cp39-abi3-win_amd64.whl", hash = "sha256:0c580952eef9bf68c4747774cde7ec1d85a6e61de97281f2dba83c7d2c806362"}, - {file = "cryptography-43.0.3-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d03b5621a135bffecad2c73e9f4deb1a0f977b9a8ffe6f8e002bf6c9d07b918c"}, - {file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:a2a431ee15799d6db9fe80c82b055bae5a752bef645bba795e8e52687c69efe3"}, - {file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:281c945d0e28c92ca5e5930664c1cefd85efe80e5c0d2bc58dd63383fda29f83"}, - {file = "cryptography-43.0.3-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:f18c716be16bc1fea8e95def49edf46b82fccaa88587a45f8dc0ff6ab5d8e0a7"}, - {file = "cryptography-43.0.3-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4a02ded6cd4f0a5562a8887df8b3bd14e822a90f97ac5e544c162899bc467664"}, - {file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:53a583b6637ab4c4e3591a15bc9db855b8d9dee9a669b550f311480acab6eb08"}, - {file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:1ec0bcf7e17c0c5669d881b1cd38c4972fade441b27bda1051665faaa89bdcaa"}, - {file = "cryptography-43.0.3-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:2ce6fae5bdad59577b44e4dfed356944fbf1d925269114c28be377692643b4ff"}, - {file = "cryptography-43.0.3.tar.gz", hash = "sha256:315b9001266a492a6ff443b61238f956b214dbec9910a081ba5b6646a055a805"}, + {file = "cryptography-44.0.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:84111ad4ff3f6253820e6d3e58be2cc2a00adb29335d4cacb5ab4d4d34f2a123"}, + {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b15492a11f9e1b62ba9d73c210e2416724633167de94607ec6069ef724fad092"}, + {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:831c3c4d0774e488fdc83a1923b49b9957d33287de923d58ebd3cec47a0ae43f"}, + {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:761817a3377ef15ac23cd7834715081791d4ec77f9297ee694ca1ee9c2c7e5eb"}, + {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:3c672a53c0fb4725a29c303be906d3c1fa99c32f58abe008a82705f9ee96f40b"}, + {file = "cryptography-44.0.0-cp37-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:4ac4c9f37eba52cb6fbeaf5b59c152ea976726b865bd4cf87883a7e7006cc543"}, + {file = "cryptography-44.0.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:ed3534eb1090483c96178fcb0f8893719d96d5274dfde98aa6add34614e97c8e"}, + {file = "cryptography-44.0.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f3f6fdfa89ee2d9d496e2c087cebef9d4fcbb0ad63c40e821b39f74bf48d9c5e"}, + {file = "cryptography-44.0.0-cp37-abi3-win32.whl", hash = "sha256:eb33480f1bad5b78233b0ad3e1b0be21e8ef1da745d8d2aecbb20671658b9053"}, + {file = "cryptography-44.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:abc998e0c0eee3c8a1904221d3f67dcfa76422b23620173e28c11d3e626c21bd"}, + {file = "cryptography-44.0.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:660cb7312a08bc38be15b696462fa7cc7cd85c3ed9c576e81f4dc4d8b2b31591"}, + {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1923cb251c04be85eec9fda837661c67c1049063305d6be5721643c22dd4e2b7"}, + {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:404fdc66ee5f83a1388be54300ae978b2efd538018de18556dde92575e05defc"}, + {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c5eb858beed7835e5ad1faba59e865109f3e52b3783b9ac21e7e47dc5554e289"}, + {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f53c2c87e0fb4b0c00fa9571082a057e37690a8f12233306161c8f4b819960b7"}, + {file = "cryptography-44.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:9e6fc8a08e116fb7c7dd1f040074c9d7b51d74a8ea40d4df2fc7aa08b76b9e6c"}, + {file = "cryptography-44.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d2436114e46b36d00f8b72ff57e598978b37399d2786fd39793c36c6d5cb1c64"}, + {file = "cryptography-44.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a01956ddfa0a6790d594f5b34fc1bfa6098aca434696a03cfdbe469b8ed79285"}, + {file = "cryptography-44.0.0-cp39-abi3-win32.whl", hash = "sha256:eca27345e1214d1b9f9490d200f9db5a874479be914199194e746c893788d417"}, + {file = "cryptography-44.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:708ee5f1bafe76d041b53a4f95eb28cdeb8d18da17e597d46d7833ee59b97ede"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:37d76e6863da3774cd9db5b409a9ecfd2c71c981c38788d3fcfaf177f447b731"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:f677e1268c4e23420c3acade68fac427fffcb8d19d7df95ed7ad17cdef8404f4"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:f5e7cb1e5e56ca0933b4873c0220a78b773b24d40d186b6738080b73d3d0a756"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:8b3e6eae66cf54701ee7d9c83c30ac0a1e3fa17be486033000f2a73a12ab507c"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:be4ce505894d15d5c5037167ffb7f0ae90b7be6f2a98f9a5c3442395501c32fa"}, + {file = "cryptography-44.0.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:62901fb618f74d7d81bf408c8719e9ec14d863086efe4185afd07c352aee1d2c"}, + {file = "cryptography-44.0.0.tar.gz", hash = "sha256:cd4e834f340b4293430701e772ec543b0fbe6c2dea510a5286fe0acabe153a02"}, ] [package.dependencies] cffi = {version = ">=1.12", markers = "platform_python_implementation != \"PyPy\""} [package.extras] -docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.1.1)"] -docstest = ["pyenchant (>=1.6.11)", "readme-renderer", "sphinxcontrib-spelling (>=4.0.1)"] -nox = ["nox"] -pep8test = ["check-sdist", "click", "mypy", "ruff"] -sdist = ["build"] +docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=3.0.0)"] +docstest = ["pyenchant (>=3)", "readme-renderer (>=30.0)", "sphinxcontrib-spelling (>=7.3.1)"] +nox = ["nox (>=2024.4.15)", "nox[uv] (>=2024.3.2)"] +pep8test = ["check-sdist", "click (>=8.0.1)", "mypy (>=1.4)", "ruff (>=0.3.6)"] +sdist = ["build (>=1.0.0)"] ssh = ["bcrypt (>=3.1.5)"] -test = ["certifi", "cryptography-vectors (==43.0.3)", "pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-xdist"] +test = ["certifi (>=2024)", "cryptography-vectors (==44.0.0)", "pretend (>=0.7)", "pytest (>=7.4.0)", "pytest-benchmark (>=4.0)", "pytest-cov (>=2.10.1)", "pytest-xdist (>=3.5.0)"] test-randomorder = ["pytest-randomly"] [[package]] @@ -503,6 +537,8 @@ version = "1.8.1" description = "A utility for ensuring Google-style docstrings stay up to date with the source code." optional = false python-versions = ">=3.6,<4.0" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "darglint-1.8.1-py3-none-any.whl", hash = "sha256:5ae11c259c17b0701618a20c3da343a3eb98b3bc4b5a83d31cdd94f5ebdced8d"}, {file = "darglint-1.8.1.tar.gz", hash = "sha256:080d5106df149b199822e7ee7deb9c012b49891538f14a11be681044f0bb20da"}, @@ -514,6 +550,8 @@ version = "0.3.9" description = "serialize all of Python" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "dill-0.3.9-py3-none-any.whl", hash = "sha256:468dff3b89520b474c0397703366b7b95eebe6303f108adf9b19da1f702be87a"}, {file = "dill-0.3.9.tar.gz", hash = "sha256:81aa267dddf68cbfe8029c42ca9ec6a4ab3b22371d1c450abc54422577b4512c"}, @@ -529,6 +567,8 @@ version = "0.3.9" description = "Distribution utilities" optional = false python-versions = "*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87"}, {file = "distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403"}, @@ -540,6 +580,8 @@ version = "1.9.0" description = "Distro - an OS platform information API" optional = false python-versions = ">=3.6" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and sys_platform == \"linux\"" files = [ {file = "distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2"}, {file = "distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed"}, @@ -551,6 +593,8 @@ version = "0.21.2" description = "Docutils -- Python Documentation Utilities" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2"}, {file = "docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f"}, @@ -562,6 +606,8 @@ version = "1.2.2" description = "Backport of PEP 654 (exception groups)" optional = false python-versions = ">=3.7" +groups = ["main", "dev"] +markers = "python_version < \"3.11\"" files = [ {file = "exceptiongroup-1.2.2-py3-none-any.whl", hash = "sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b"}, {file = "exceptiongroup-1.2.2.tar.gz", hash = "sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc"}, @@ -572,13 +618,15 @@ test = ["pytest (>=6)"] [[package]] name = "fastapi" -version = "0.115.7" +version = "0.115.8" 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.7-py3-none-any.whl", hash = "sha256:eb6a8c8bf7f26009e8147111ff15b5177a0e19bb4a45bc3486ab14804539d21e"}, - {file = "fastapi-0.115.7.tar.gz", hash = "sha256:0f106da6c01d88a6786b3248fb4d7a940d071f6f488488898ad5d354b25ed015"}, + {file = "fastapi-0.115.8-py3-none-any.whl", hash = "sha256:753a96dd7e036b34eeef8babdfcfe3f28ff79648f86551eb36bfc1b0bf4a8cbf"}, + {file = "fastapi-0.115.8.tar.gz", hash = "sha256:0ce9111231720190473e222cdf0f07f7206ad7e53ea02beb1d2dc36e2f0741e9"}, ] [package.dependencies] @@ -596,6 +644,8 @@ version = "3.17.0" description = "A platform independent file lock." optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "filelock-3.17.0-py3-none-any.whl", hash = "sha256:533dc2f7ba78dc2f0f531fc6c4940addf7b70a481e269a5a3b93be94ffbe8338"}, {file = "filelock-3.17.0.tar.gz", hash = "sha256:ee4e77401ef576ebb38cd7f13b9b28893194acc20a8e68e18730ba9c0e54660e"}, @@ -612,6 +662,7 @@ version = "3.1.1" description = "Lightweight in-process concurrent programming" optional = false python-versions = ">=3.7" +groups = ["main", "dev"] files = [ {file = "greenlet-3.1.1-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:0bbae94a29c9e5c7e4a2b7f0aae5c17e8e90acbfd3bf6270eeba60c39fce3563"}, {file = "greenlet-3.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0fde093fb93f35ca72a556cf72c92ea3ebfda3d79fc35bb19fbe685853869a83"}, @@ -687,6 +738,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.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"] @@ -698,6 +750,8 @@ version = "23.0.0" description = "WSGI HTTP Server for UNIX" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "gunicorn-23.0.0-py3-none-any.whl", hash = "sha256:ec400d38950de4dfd418cff8328b2c8faed0edb0d517d3394e457c317908ca4d"}, {file = "gunicorn-23.0.0.tar.gz", hash = "sha256:f014447a0101dc57e294f6c18ca6b40227a4c90e9bdb586042628030cba004ec"}, @@ -719,6 +773,8 @@ version = "0.14.0" description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" optional = false python-versions = ">=3.7" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761"}, {file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"}, @@ -730,6 +786,8 @@ version = "1.0.7" description = "A minimal low-level HTTP client." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "httpcore-1.0.7-py3-none-any.whl", hash = "sha256:a3fff8f43dc260d5bd363d9f9cf1830fa3a458b332856f34282de498ed420edd"}, {file = "httpcore-1.0.7.tar.gz", hash = "sha256:8551cb62a169ec7162ac7be8d4817d561f60e08eaa485234898414bb5a8a0b4c"}, @@ -751,6 +809,8 @@ version = "0.28.1" description = "The next generation HTTP client." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad"}, {file = "httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc"}, @@ -775,6 +835,8 @@ version = "1.5.0" description = "A tool for generating OIDC identities" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "id-1.5.0-py3-none-any.whl", hash = "sha256:f1434e1cef91f2cbb8a4ec64663d5a23b9ed43ef44c4c957d02583d61714c658"}, {file = "id-1.5.0.tar.gz", hash = "sha256:292cb8a49eacbbdbce97244f47a97b4c62540169c976552e497fd57df0734c1d"}, @@ -794,6 +856,8 @@ version = "2.6.6" description = "File identification library for Python" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "identify-2.6.6-py2.py3-none-any.whl", hash = "sha256:cbd1810bce79f8b671ecb20f53ee0ae8e86ae84b557de31d89709dc2a48ba881"}, {file = "identify-2.6.6.tar.gz", hash = "sha256:7bec12768ed44ea4761efb47806f0a41f86e7c0a5fdf5950d4648c90eca7e251"}, @@ -808,6 +872,8 @@ version = "3.10" description = "Internationalized Domain Names in Applications (IDNA)" optional = false python-versions = ">=3.6" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3"}, {file = "idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9"}, @@ -822,6 +888,8 @@ version = "8.6.1" description = "Read metadata from Python packages" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and python_version <= \"3.11\" or python_full_version < \"3.10.2\"" files = [ {file = "importlib_metadata-8.6.1-py3-none-any.whl", hash = "sha256:02a89390c1e15fdfdc0d7c6b25cb3e62650d0494005c97d6f148bf5b9787525e"}, {file = "importlib_metadata-8.6.1.tar.gz", hash = "sha256:310b41d755445d74569f993ccfc22838295d9fe005425094fad953d7f15c8580"}, @@ -845,6 +913,8 @@ version = "2.0.0" description = "brain-dead simple config-ini parsing" optional = false python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, @@ -856,6 +926,8 @@ version = "3.4.0" description = "Utility functions for Python class constructs" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790"}, {file = "jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd"}, @@ -874,6 +946,8 @@ version = "6.0.1" description = "Useful decorators and context managers" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "jaraco.context-6.0.1-py3-none-any.whl", hash = "sha256:f797fc481b490edb305122c9181830a3a5b76d84ef6d1aef2fb9b47ab956f9e4"}, {file = "jaraco_context-6.0.1.tar.gz", hash = "sha256:9bae4ea555cf0b14938dc0aee7c9f32ed303aa20a3b73e7dc80111628792d1b3"}, @@ -892,6 +966,8 @@ version = "4.1.0" description = "Functools like those found in stdlib" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "jaraco.functools-4.1.0-py3-none-any.whl", hash = "sha256:ad159f13428bc4acbf5541ad6dec511f91573b90fba04df61dafa2a1231cf649"}, {file = "jaraco_functools-4.1.0.tar.gz", hash = "sha256:70f7e0e2ae076498e212562325e805204fc092d7b4c17e0e86c959e249701a9d"}, @@ -914,6 +990,8 @@ version = "0.8.0" description = "Low-level, pure Python DBus protocol wrapper." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"linux\" and (python_version <= \"3.11\" or python_version >= \"3.12\")" files = [ {file = "jeepney-0.8.0-py3-none-any.whl", hash = "sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755"}, {file = "jeepney-0.8.0.tar.gz", hash = "sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806"}, @@ -929,6 +1007,8 @@ version = "3.1.5" description = "A very fast and expressive template engine." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "jinja2-3.1.5-py3-none-any.whl", hash = "sha256:aba0f4dc9ed8013c424088f68a5c226f7d6097ed89b246d7749c2ec4175c6adb"}, {file = "jinja2-3.1.5.tar.gz", hash = "sha256:8fefff8dc3034e27bb80d67c671eb8a9bc424c0ef4c0826edbff304cceff43bb"}, @@ -946,6 +1026,8 @@ version = "25.6.0" description = "Store and access your passwords safely." optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "keyring-25.6.0-py3-none-any.whl", hash = "sha256:552a3f7af126ece7ed5c89753650eec89c7eaae8617d0aa4d9ad2b75111266bd"}, {file = "keyring-25.6.0.tar.gz", hash = "sha256:0b39998aa941431eb3d9b0d4b2460bc773b9df6fed7621c2dfb291a7e0187a66"}, @@ -975,6 +1057,8 @@ version = "0.4" description = "Makes it easy to load subpackages and functions on demand." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "lazy_loader-0.4-py3-none-any.whl", hash = "sha256:342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc"}, {file = "lazy_loader-0.4.tar.gz", hash = "sha256:47c75182589b91a4e1a85a136c074285a5ad4d9f39c63e0d7fb76391c4574cd1"}, @@ -994,6 +1078,8 @@ version = "1.3.8" description = "A super-fast templating language that borrows the best ideas from the existing templating languages." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "Mako-1.3.8-py3-none-any.whl", hash = "sha256:42f48953c7eb91332040ff567eb7eea69b22e7a4affbc5ba8e845e8f730f6627"}, {file = "mako-1.3.8.tar.gz", hash = "sha256:577b97e414580d3e088d47c2dbbe9594aa7a5146ed2875d4dfa9075af2dd3cc8"}, @@ -1013,6 +1099,8 @@ version = "3.0.0" description = "Python port of markdown-it. Markdown parsing, done right!" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"}, {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"}, @@ -1037,6 +1125,8 @@ version = "3.0.2" description = "Safely add untrusted strings to HTML/XML markup." optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8"}, {file = "MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158"}, @@ -1107,6 +1197,8 @@ version = "0.1.2" description = "Markdown URL utilities" optional = false python-versions = ">=3.7" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"}, {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"}, @@ -1118,6 +1210,8 @@ version = "10.6.0" description = "More routines for operating on iterables, beyond itertools" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "(python_version <= \"3.11\" or python_version >= \"3.12\") and (platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "more-itertools-10.6.0.tar.gz", hash = "sha256:2cd7fad1009c31cc9fb6a035108509e6547547a7a738374f10bd49a09eb3ee3b"}, {file = "more_itertools-10.6.0-py3-none-any.whl", hash = "sha256:6eb054cb4b6db1473f6e15fcc676a08e4732548acd47c708f0e179c2c7c01e89"}, @@ -1129,6 +1223,8 @@ version = "0.2.20" description = "Python binding to Ammonia HTML sanitizer Rust crate" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "nh3-0.2.20-cp313-cp313t-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:e1061a4ab6681f6bdf72b110eea0c4e1379d57c9de937db3be4202f7ad6043db"}, {file = "nh3-0.2.20-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb4254b1dac4a1ee49919a5b3f1caf9803ea8dada1816d9e8289e63d3cd0dd9a"}, @@ -1162,71 +1258,21 @@ version = "1.9.1" description = "Node.js virtual environment builder" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9"}, {file = "nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f"}, ] -[[package]] -name = "numpy" -version = "2.0.2" -description = "Fundamental package for array computing in Python" -optional = false -python-versions = ">=3.9" -files = [ - {file = "numpy-2.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:51129a29dbe56f9ca83438b706e2e69a39892b5eda6cedcb6b0c9fdc9b0d3ece"}, - {file = "numpy-2.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f15975dfec0cf2239224d80e32c3170b1d168335eaedee69da84fbe9f1f9cd04"}, - {file = "numpy-2.0.2-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:8c5713284ce4e282544c68d1c3b2c7161d38c256d2eefc93c1d683cf47683e66"}, - {file = "numpy-2.0.2-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:becfae3ddd30736fe1889a37f1f580e245ba79a5855bff5f2a29cb3ccc22dd7b"}, - {file = "numpy-2.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2da5960c3cf0df7eafefd806d4e612c5e19358de82cb3c343631188991566ccd"}, - {file = "numpy-2.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:496f71341824ed9f3d2fd36cf3ac57ae2e0165c143b55c3a035ee219413f3318"}, - {file = "numpy-2.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:a61ec659f68ae254e4d237816e33171497e978140353c0c2038d46e63282d0c8"}, - {file = "numpy-2.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d731a1c6116ba289c1e9ee714b08a8ff882944d4ad631fd411106a30f083c326"}, - {file = "numpy-2.0.2-cp310-cp310-win32.whl", hash = "sha256:984d96121c9f9616cd33fbd0618b7f08e0cfc9600a7ee1d6fd9b239186d19d97"}, - {file = "numpy-2.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:c7b0be4ef08607dd04da4092faee0b86607f111d5ae68036f16cc787e250a131"}, - {file = "numpy-2.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:49ca4decb342d66018b01932139c0961a8f9ddc7589611158cb3c27cbcf76448"}, - {file = "numpy-2.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:11a76c372d1d37437857280aa142086476136a8c0f373b2e648ab2c8f18fb195"}, - {file = "numpy-2.0.2-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:807ec44583fd708a21d4a11d94aedf2f4f3c3719035c76a2bbe1fe8e217bdc57"}, - {file = "numpy-2.0.2-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8cafab480740e22f8d833acefed5cc87ce276f4ece12fdaa2e8903db2f82897a"}, - {file = "numpy-2.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a15f476a45e6e5a3a79d8a14e62161d27ad897381fecfa4a09ed5322f2085669"}, - {file = "numpy-2.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:13e689d772146140a252c3a28501da66dfecd77490b498b168b501835041f951"}, - {file = "numpy-2.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9ea91dfb7c3d1c56a0e55657c0afb38cf1eeae4544c208dc465c3c9f3a7c09f9"}, - {file = "numpy-2.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c1c9307701fec8f3f7a1e6711f9089c06e6284b3afbbcd259f7791282d660a15"}, - {file = "numpy-2.0.2-cp311-cp311-win32.whl", hash = "sha256:a392a68bd329eafac5817e5aefeb39038c48b671afd242710b451e76090e81f4"}, - {file = "numpy-2.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:286cd40ce2b7d652a6f22efdfc6d1edf879440e53e76a75955bc0c826c7e64dc"}, - {file = "numpy-2.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:df55d490dea7934f330006d0f81e8551ba6010a5bf035a249ef61a94f21c500b"}, - {file = "numpy-2.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8df823f570d9adf0978347d1f926b2a867d5608f434a7cff7f7908c6570dcf5e"}, - {file = "numpy-2.0.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:9a92ae5c14811e390f3767053ff54eaee3bf84576d99a2456391401323f4ec2c"}, - {file = "numpy-2.0.2-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:a842d573724391493a97a62ebbb8e731f8a5dcc5d285dfc99141ca15a3302d0c"}, - {file = "numpy-2.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05e238064fc0610c840d1cf6a13bf63d7e391717d247f1bf0318172e759e692"}, - {file = "numpy-2.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0123ffdaa88fa4ab64835dcbde75dcdf89c453c922f18dced6e27c90d1d0ec5a"}, - {file = "numpy-2.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:96a55f64139912d61de9137f11bf39a55ec8faec288c75a54f93dfd39f7eb40c"}, - {file = "numpy-2.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ec9852fb39354b5a45a80bdab5ac02dd02b15f44b3804e9f00c556bf24b4bded"}, - {file = "numpy-2.0.2-cp312-cp312-win32.whl", hash = "sha256:671bec6496f83202ed2d3c8fdc486a8fc86942f2e69ff0e986140339a63bcbe5"}, - {file = "numpy-2.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:cfd41e13fdc257aa5778496b8caa5e856dc4896d4ccf01841daee1d96465467a"}, - {file = "numpy-2.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9059e10581ce4093f735ed23f3b9d283b9d517ff46009ddd485f1747eb22653c"}, - {file = "numpy-2.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:423e89b23490805d2a5a96fe40ec507407b8ee786d66f7328be214f9679df6dd"}, - {file = "numpy-2.0.2-cp39-cp39-macosx_14_0_arm64.whl", hash = "sha256:2b2955fa6f11907cf7a70dab0d0755159bca87755e831e47932367fc8f2f2d0b"}, - {file = "numpy-2.0.2-cp39-cp39-macosx_14_0_x86_64.whl", hash = "sha256:97032a27bd9d8988b9a97a8c4d2c9f2c15a81f61e2f21404d7e8ef00cb5be729"}, - {file = "numpy-2.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1e795a8be3ddbac43274f18588329c72939870a16cae810c2b73461c40718ab1"}, - {file = "numpy-2.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26b258c385842546006213344c50655ff1555a9338e2e5e02a0756dc3e803dd"}, - {file = "numpy-2.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5fec9451a7789926bcf7c2b8d187292c9f93ea30284802a0ab3f5be8ab36865d"}, - {file = "numpy-2.0.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:9189427407d88ff25ecf8f12469d4d39d35bee1db5d39fc5c168c6f088a6956d"}, - {file = "numpy-2.0.2-cp39-cp39-win32.whl", hash = "sha256:905d16e0c60200656500c95b6b8dca5d109e23cb24abc701d41c02d74c6b3afa"}, - {file = "numpy-2.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:a3f4ab0caa7f053f6797fcd4e1e25caee367db3112ef2b6ef82d749530768c73"}, - {file = "numpy-2.0.2-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:7f0a0c6f12e07fa94133c8a67404322845220c06a9e80e85999afe727f7438b8"}, - {file = "numpy-2.0.2-pp39-pypy39_pp73-macosx_14_0_x86_64.whl", hash = "sha256:312950fdd060354350ed123c0e25a71327d3711584beaef30cdaa93320c392d4"}, - {file = "numpy-2.0.2-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:26df23238872200f63518dd2aa984cfca675d82469535dc7162dc2ee52d9dd5c"}, - {file = "numpy-2.0.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a46288ec55ebbd58947d31d72be2c63cbf839f0a63b49cb755022310792a3385"}, - {file = "numpy-2.0.2.tar.gz", hash = "sha256:883c987dee1880e2a864ab0dc9892292582510604156762362d9326444636e78"}, -] - [[package]] name = "numpy" version = "2.2.2" description = "Fundamental package for array computing in Python" optional = false python-versions = ">=3.10" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "numpy-2.2.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7079129b64cb78bdc8d611d1fd7e8002c0a2565da6a47c4df8062349fee90e3e"}, {file = "numpy-2.2.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2ec6c689c61df613b783aeb21f945c4cbe6c51c28cb70aae8430577ab39f163e"}, @@ -1291,6 +1337,8 @@ version = "1.3.0.post0" description = "Capture the outcome of Python function calls." optional = false python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "outcome-1.3.0.post0-py2.py3-none-any.whl", hash = "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b"}, {file = "outcome-1.3.0.post0.tar.gz", hash = "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8"}, @@ -1305,6 +1353,8 @@ version = "24.2" description = "Core utilities for Python packages" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "packaging-24.2-py3-none-any.whl", hash = "sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759"}, {file = "packaging-24.2.tar.gz", hash = "sha256:c228a6dc5e932d346bc5739379109d49e8853dd8223571c7c5b55260edc0b97f"}, @@ -1316,6 +1366,8 @@ version = "2.2.3" description = "Powerful data structures for data analysis, time series, and statistics" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pandas-2.2.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1948ddde24197a0f7add2bdc4ca83bf2b1ef84a1bc8ccffd95eda17fd836ecb5"}, {file = "pandas-2.2.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:381175499d3802cde0eabbaf6324cce0c4f5d52ca6f8c377c29ad442f50f6348"}, @@ -1402,6 +1454,8 @@ version = "11.1.0" description = "Python Imaging Library (Fork)" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pillow-11.1.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:e1abe69aca89514737465752b4bcaf8016de61b3be1397a8fc260ba33321b3a8"}, {file = "pillow-11.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c640e5a06869c75994624551f45e5506e4256562ead981cce820d5ab39ae2192"}, @@ -1484,41 +1538,14 @@ 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" -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" -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" description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`." optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "platformdirs-4.3.6-py3-none-any.whl", hash = "sha256:73e575e1408ab8103900836b97580d5307456908a03e92031bab39e4554cc3fb"}, {file = "platformdirs-4.3.6.tar.gz", hash = "sha256:357fb2acbc885b0419afd3ce3ed34564c13c9b95c89360cd9563f73aa5e2b907"}, @@ -1535,6 +1562,8 @@ version = "1.49.1" description = "A high-level API to automate web browsers" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "playwright-1.49.1-py3-none-macosx_10_13_x86_64.whl", hash = "sha256:1041ffb45a0d0bc44d698d3a5aa3ac4b67c9bd03540da43a0b70616ad52592b8"}, {file = "playwright-1.49.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9f38ed3d0c1f4e0a6d1c92e73dd9a61f8855133249d6f0cec28648d38a7137be"}, @@ -1555,6 +1584,8 @@ version = "5.24.1" description = "An open-source, interactive data visualization library for Python" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "plotly-5.24.1-py3-none-any.whl", hash = "sha256:f67073a1e637eb0dc3e46324d9d51e2fe76e9727c892dde64ddf1e1b51f29089"}, {file = "plotly-5.24.1.tar.gz", hash = "sha256:dbc8ac8339d248a4bcc36e08a5659bacfe1b079390b8953533f4eb22169b4bae"}, @@ -1570,6 +1601,8 @@ version = "1.5.0" description = "plugin and hook calling mechanisms for python" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pluggy-1.5.0-py3-none-any.whl", hash = "sha256:44e1ad92c8ca002de6377e165f3e0f1be63266ab4d554740532335b9d75ea669"}, {file = "pluggy-1.5.0.tar.gz", hash = "sha256:2cffa88e94fdc978c4c574f15f9e59b7f4201d439195c3715ca9e2486f1d0cf1"}, @@ -1585,6 +1618,8 @@ version = "4.1.0" description = "A framework for managing and maintaining multi-language pre-commit hooks." optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pre_commit-4.1.0-py2.py3-none-any.whl", hash = "sha256:d29e7cb346295bcc1cc75fc3e92e343495e3ea0196c9ec6ba53f49f10ab6ae7b"}, {file = "pre_commit-4.1.0.tar.gz", hash = "sha256:ae3f018575a588e30dfddfab9a05448bfbd6b73d78709617b5a2b853549716d4"}, @@ -1603,6 +1638,8 @@ version = "6.1.1" description = "Cross-platform lib for process and system monitoring in Python." optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "psutil-6.1.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:9ccc4316f24409159897799b83004cb1e24f9819b0dcf9c0b68bdcb6cefee6a8"}, {file = "psutil-6.1.1-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:ca9609c77ea3b8481ab005da74ed894035936223422dc591d6772b147421f777"}, @@ -1633,6 +1670,8 @@ version = "9.0.0" description = "Get CPU info with pure Python" optional = false python-versions = "*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "py-cpuinfo-9.0.0.tar.gz", hash = "sha256:3cdbbf3fac90dc6f118bfd64384f309edeadd902d7c8fb17f02ffa1fc3f49690"}, {file = "py_cpuinfo-9.0.0-py3-none-any.whl", hash = "sha256:859625bc251f64e21f077d099d4162689c762b5d6a4c3c97553d56241c9674d5"}, @@ -1644,20 +1683,24 @@ version = "2.22" description = "C parser in Python" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] files = [ {file = "pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc"}, {file = "pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6"}, ] +markers = {main = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"linux\" and platform_python_implementation != \"PyPy\" and (python_version <= \"3.11\" or python_version >= \"3.12\")", dev = "python_version <= \"3.11\" or python_version >= \"3.12\""} [[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] @@ -1675,6 +1718,8 @@ version = "2.27.2" description = "Core functionality for Pydantic validation and serialization" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pydantic_core-2.27.2-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:2d367ca20b2f14095a8f4fa1210f5a7b78b8a20009ecced6b12818f455b1e9fa"}, {file = "pydantic_core-2.27.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:491a2b73db93fab69731eaee494f320faa4e093dbed776be1a829c2eb222c34c"}, @@ -1787,6 +1832,8 @@ version = "12.0.0" description = "A rough port of Node.js's EventEmitter to Python with a few tricks of its own" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pyee-12.0.0-py3-none-any.whl", hash = "sha256:7b14b74320600049ccc7d0e0b1becd3b4bd0a03c745758225e31a59f4095c990"}, {file = "pyee-12.0.0.tar.gz", hash = "sha256:c480603f4aa2927d4766eb41fa82793fe60a82cbfdb8d688e0d08c55a534e145"}, @@ -1804,6 +1851,8 @@ version = "2.19.1" description = "Pygments is a syntax highlighting package written in Python." optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c"}, {file = "pygments-2.19.1.tar.gz", hash = "sha256:61c16d2a8576dc0649d9f39e089b5f02bcd27fba10d8fb4dcc28173f7a45151f"}, @@ -1818,6 +1867,8 @@ version = "1.2.0" description = "Wrappers to call pyproject.toml-based build backend hooks." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pyproject_hooks-1.2.0-py3-none-any.whl", hash = "sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913"}, {file = "pyproject_hooks-1.2.0.tar.gz", hash = "sha256:1e859bd5c40fae9448642dd871adf459e5e2084186e8d2c2a79a824c970da1f8"}, @@ -1825,21 +1876,25 @@ files = [ [[package]] name = "pyright" -version = "1.1.334" +version = "1.1.393" 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.393-py3-none-any.whl", hash = "sha256:8320629bb7a44ca90944ba599390162bf59307f3d9fb6e27da3b7011b8c17ae5"}, + {file = "pyright-1.1.393.tar.gz", hash = "sha256:aeeb7ff4e0364775ef416a80111613f91a05c8e01e58ecfefc370ca0db7aed9c"}, ] [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" @@ -1847,6 +1902,8 @@ version = "1.7.1" description = "A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information." optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "PySocks-1.7.1-py27-none-any.whl", hash = "sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299"}, {file = "PySocks-1.7.1-py3-none-any.whl", hash = "sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5"}, @@ -1859,6 +1916,8 @@ version = "8.3.4" description = "pytest: simple powerful testing with Python" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pytest-8.3.4-py3-none-any.whl", hash = "sha256:50e16d954148559c9a74109af1eaf0c945ba2d8f30f0a3d3335edde19788b6f6"}, {file = "pytest-8.3.4.tar.gz", hash = "sha256:965370d062bce11e73868e0335abac31b4d3de0e82f4007408d242b4f8610761"}, @@ -1877,13 +1936,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] @@ -1899,6 +1960,8 @@ version = "2.1.0" description = "pytest plugin for URL based testing" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pytest_base_url-2.1.0-py3-none-any.whl", hash = "sha256:3ad15611778764d451927b2a53240c1a7a591b521ea44cebfe45849d2d2812e6"}, {file = "pytest_base_url-2.1.0.tar.gz", hash = "sha256:02748589a54f9e63fcbe62301d6b0496da0d10231b753e950c63e03aee745d45"}, @@ -1917,6 +1980,8 @@ version = "5.1.0" description = "A ``pytest`` fixture for benchmarking code. It will group the tests into rounds that are calibrated to the chosen timer." optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pytest-benchmark-5.1.0.tar.gz", hash = "sha256:9ea661cdc292e8231f7cd4c10b0319e56a2118e2c09d9f50e1b3d150d2aca105"}, {file = "pytest_benchmark-5.1.0-py3-none-any.whl", hash = "sha256:922de2dfa3033c227c96da942d1878191afa135a29485fb942e85dff1c592c89"}, @@ -1931,12 +1996,47 @@ aspect = ["aspectlib"] elasticsearch = ["elasticsearch"] histogram = ["pygal", "pygaljs", "setuptools"] +[[package]] +name = "pytest-codspeed" +version = "3.2.0" +description = "Pytest plugin to create CodSpeed benchmarks" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" +files = [ + {file = "pytest_codspeed-3.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5165774424c7ab8db7e7acdb539763a0e5657996effefdf0664d7fd95158d34"}, + {file = "pytest_codspeed-3.2.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9bd55f92d772592c04a55209950c50880413ae46876e66bd349ef157075ca26c"}, + {file = "pytest_codspeed-3.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4cf6f56067538f4892baa8d7ab5ef4e45bb59033be1ef18759a2c7fc55b32035"}, + {file = "pytest_codspeed-3.2.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:39a687b05c3d145642061b45ea78e47e12f13ce510104d1a2cda00eee0e36f58"}, + {file = "pytest_codspeed-3.2.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:46a1afaaa1ac4c2ca5b0700d31ac46d80a27612961d031067d73c6ccbd8d3c2b"}, + {file = "pytest_codspeed-3.2.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c48ce3af3dfa78413ed3d69d1924043aa1519048dbff46edccf8f35a25dab3c2"}, + {file = "pytest_codspeed-3.2.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:66692506d33453df48b36a84703448cb8b22953eea51f03fbb2eb758dc2bdc4f"}, + {file = "pytest_codspeed-3.2.0-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:479774f80d0bdfafa16112700df4dbd31bf2a6757fac74795fd79c0a7b3c389b"}, + {file = "pytest_codspeed-3.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:109f9f4dd1088019c3b3f887d003b7d65f98a7736ca1d457884f5aa293e8e81c"}, + {file = "pytest_codspeed-3.2.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2f69a03b52c9bb041aec1b8ee54b7b6c37a6d0a948786effa4c71157765b6da"}, + {file = "pytest_codspeed-3.2.0-py3-none-any.whl", hash = "sha256:54b5c2e986d6a28e7b0af11d610ea57bd5531cec8326abe486f1b55b09d91c39"}, + {file = "pytest_codspeed-3.2.0.tar.gz", hash = "sha256:f9d1b1a3b2c69cdc0490a1e8b1ced44bffbd0e8e21d81a7160cfdd923f6e8155"}, +] + +[package.dependencies] +cffi = ">=1.17.1" +pytest = ">=3.8" +rich = ">=13.8.1" + +[package.extras] +compat = ["pytest-benchmark (>=5.0.0,<5.1.0)", "pytest-xdist (>=3.6.1,<3.7.0)"] +lint = ["mypy (>=1.11.2,<1.12.0)", "ruff (>=0.6.5,<0.7.0)"] +test = ["pytest (>=7.0,<8.0)", "pytest-cov (>=4.0.0,<4.1.0)"] + [[package]] name = "pytest-cov" version = "6.0.0" description = "Pytest plugin for measuring coverage." optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pytest-cov-6.0.0.tar.gz", hash = "sha256:fde0b595ca248bb8e2d76f020b465f3b107c9632e6a1d1705f17834c89dcadc0"}, {file = "pytest_cov-6.0.0-py3-none-any.whl", hash = "sha256:eee6f1b9e61008bd34975a4d5bab25801eb31898b032dd55addc93e96fcaaa35"}, @@ -1955,6 +2055,8 @@ version = "3.14.0" description = "Thin-wrapper around the mock package for easier use with pytest" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "pytest-mock-3.14.0.tar.gz", hash = "sha256:2719255a1efeceadbc056d6bf3df3d1c5015530fb40cf347c0f9afac88410bd0"}, {file = "pytest_mock-3.14.0-py3-none-any.whl", hash = "sha256:0b72c38033392a5f4621342fe11e9219ac11ec9d375f8e2a0c164539e0d70f6f"}, @@ -1968,13 +2070,15 @@ dev = ["pre-commit", "pytest-asyncio", "tox"] [[package]] name = "pytest-playwright" -version = "0.6.2" +version = "0.7.0" description = "A pytest wrapper with fixtures for Playwright to automate web browsers" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "pytest_playwright-0.6.2-py3-none-any.whl", hash = "sha256:0eff73bebe497b0158befed91e2f5fe94cfa17181f8b3acf575beed84e7e9043"}, - {file = "pytest_playwright-0.6.2.tar.gz", hash = "sha256:ff4054b19aa05df096ac6f74f0572591566aaf0f6d97f6cb9674db8a4d4ed06c"}, + {file = "pytest_playwright-0.7.0-py3-none-any.whl", hash = "sha256:2516d0871fa606634bfe32afbcc0342d68da2dbff97fe3459849e9c428486da2"}, + {file = "pytest_playwright-0.7.0.tar.gz", hash = "sha256:b3f2ea514bbead96d26376fac182f68dcd6571e7cb41680a89ff1673c05d60b6"}, ] [package.dependencies] @@ -1989,6 +2093,8 @@ 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 = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"}, {file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"}, @@ -2003,6 +2109,8 @@ version = "4.11.2" description = "Engine.IO server and client for Python" optional = false python-versions = ">=3.6" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python_engineio-4.11.2-py3-none-any.whl", hash = "sha256:f0971ac4c65accc489154fe12efd88f53ca8caf04754c46a66e85f5102ef22ad"}, {file = "python_engineio-4.11.2.tar.gz", hash = "sha256:145bb0daceb904b4bb2d3eb2d93f7dbb7bb87a6a0c4f20a94cc8654dec977129"}, @@ -2022,6 +2130,8 @@ version = "0.0.20" description = "A streaming multipart parser for Python" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python_multipart-0.0.20-py3-none-any.whl", hash = "sha256:8a62d3a8335e06589fe01f2a3e178cdcc632f3fbe0d492ad9ee0ec35aab1f104"}, {file = "python_multipart-0.0.20.tar.gz", hash = "sha256:8dd0cab45b8e23064ae09147625994d090fa46f5b0d1e13af944c331a7fa9d13"}, @@ -2033,6 +2143,8 @@ version = "8.0.4" description = "A Python slugify application that also handles Unicode" optional = false python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python-slugify-8.0.4.tar.gz", hash = "sha256:59202371d1d05b54a9e7720c5e038f928f45daaffe41dd10822f3907b937c856"}, {file = "python_slugify-8.0.4-py2.py3-none-any.whl", hash = "sha256:276540b79961052b66b7d116620b36518847f52d5fd9e3a70164fc8c50faa6b8"}, @@ -2050,6 +2162,8 @@ version = "5.12.1" description = "Socket.IO server and client for Python" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "python_socketio-5.12.1-py3-none-any.whl", hash = "sha256:24a0ea7cfff0e021eb28c68edbf7914ee4111bdf030b95e4d250c4dc9af7a386"}, {file = "python_socketio-5.12.1.tar.gz", hash = "sha256:0299ff1f470b676c09c1bfab1dead25405077d227b2c13cf217a34dadc68ba9c"}, @@ -2066,13 +2180,15 @@ docs = ["sphinx"] [[package]] name = "pytz" -version = "2024.2" +version = "2025.1" description = "World timezone definitions, modern and historical" optional = false python-versions = "*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "pytz-2024.2-py2.py3-none-any.whl", hash = "sha256:31c7c1817eb7fae7ca4b8c7ee50c72f93aa2dd863de768e1ef4245d426aa0725"}, - {file = "pytz-2024.2.tar.gz", hash = "sha256:2aa355083c50a0f93fa581709deac0c9ad65cca8a9e9beac660adcbd493c798a"}, + {file = "pytz-2025.1-py2.py3-none-any.whl", hash = "sha256:89dd22dca55b46eac6eda23b2d72721bf1bdfef212645d81513ef5d03038de57"}, + {file = "pytz-2025.1.tar.gz", hash = "sha256:c2db42be2a2518b28e65f9207c4d05e6ff547d1efa4086469ef855e4ab70178e"}, ] [[package]] @@ -2081,6 +2197,8 @@ version = "0.2.3" description = "A (partial) reimplementation of pywin32 using ctypes/cffi" optional = false python-versions = ">=3.6" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"win32\" and (python_version <= \"3.11\" or python_version >= \"3.12\")" files = [ {file = "pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755"}, {file = "pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8"}, @@ -2092,6 +2210,8 @@ version = "6.0.2" description = "YAML parser and emitter for Python" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086"}, {file = "PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf"}, @@ -2154,6 +2274,8 @@ version = "44.0" description = "readme_renderer is a library for rendering readme descriptions for Warehouse" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "readme_renderer-44.0-py3-none-any.whl", hash = "sha256:2fbca89b81a08526aadf1357a8c2ae889ec05fb03f5da67f9769c9a592166151"}, {file = "readme_renderer-44.0.tar.gz", hash = "sha256:8712034eabbfa6805cacf1402b4eeb2a73028f72d1166d6f5cb7f9c047c5d1e1"}, @@ -2173,6 +2295,8 @@ version = "5.2.1" description = "Python client for Redis database and key-value store" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "redis-5.2.1-py3-none-any.whl", hash = "sha256:ee7e1056b9aea0f04c6c2ed59452947f34c4940ee025f5dd83e6a6418b6989e4"}, {file = "redis-5.2.1.tar.gz", hash = "sha256:16f2e22dff21d5125e8481515e386711a34cbec50f0e44413dd7d9c060a54e0f"}, @@ -2185,43 +2309,28 @@ async-timeout = {version = ">=4.0.3", markers = "python_full_version < \"3.11.3\ hiredis = ["hiredis (>=3.0.0)"] ocsp = ["cryptography (>=36.0.1)", "pyopenssl (==23.2.1)", "requests (>=2.31.0)"] -[[package]] -name = "reflex-chakra" -version = "0.6.3" -description = "reflex using chakra components" -optional = false -python-versions = "<4.0,>=3.9" -files = [ - {file = "reflex_chakra-0.6.3-py3-none-any.whl", hash = "sha256:f3b92ba399451986ae5d09341265ca1e134edfdc2fab3a57ea83b7f652469d9a"}, - {file = "reflex_chakra-0.6.3.tar.gz", hash = "sha256:ff7c1c7638809c99104997bffbf861793c832f6d2288e30bd4ace65fec0f40e3"}, -] - -[package.dependencies] -reflex = ">=0.6.0a" - [[package]] name = "reflex-hosting-cli" -version = "0.1.32" +version = "0.1.34" 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.34-py3-none-any.whl", hash = "sha256:eabc4dc7bf68e022a9388614c1a35b5ab36b01021df063d0c3356eda0e245264"}, + {file = "reflex_hosting_cli-0.1.34.tar.gz", hash = "sha256:07be37fda6dcede0a5d4bc1fd1786d9a3df5ad4e49dc1b6ba335418563cfecec"}, ] [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" @@ -2229,6 +2338,8 @@ version = "2.32.3" description = "Python HTTP for Humans." optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "requests-2.32.3-py3-none-any.whl", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6"}, {file = "requests-2.32.3.tar.gz", hash = "sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760"}, @@ -2250,6 +2361,8 @@ version = "1.0.0" description = "A utility belt for advanced users of python-requests" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "requests-toolbelt-1.0.0.tar.gz", hash = "sha256:7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6"}, {file = "requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06"}, @@ -2264,6 +2377,8 @@ version = "2.0.0" description = "Validating URI References per RFC 3986" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "rfc3986-2.0.0-py2.py3-none-any.whl", hash = "sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd"}, {file = "rfc3986-2.0.0.tar.gz", hash = "sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c"}, @@ -2278,6 +2393,8 @@ version = "13.9.4" description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" optional = false python-versions = ">=3.8.0" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90"}, {file = "rich-13.9.4.tar.gz", hash = "sha256:439594978a49a09530cff7ebc4b5c7103ef57baf48d5ea3184f21d9a2befa098"}, @@ -2293,29 +2410,31 @@ jupyter = ["ipywidgets (>=7.5.1,<9)"] [[package]] name = "ruff" -version = "0.8.2" +version = "0.9.3" description = "An extremely fast Python linter and code formatter, written in Rust." optional = false python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "ruff-0.8.2-py3-none-linux_armv6l.whl", hash = "sha256:c49ab4da37e7c457105aadfd2725e24305ff9bc908487a9bf8d548c6dad8bb3d"}, - {file = "ruff-0.8.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ec016beb69ac16be416c435828be702ee694c0d722505f9c1f35e1b9c0cc1bf5"}, - {file = "ruff-0.8.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:f05cdf8d050b30e2ba55c9b09330b51f9f97d36d4673213679b965d25a785f3c"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:60f578c11feb1d3d257b2fb043ddb47501ab4816e7e221fbb0077f0d5d4e7b6f"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cbd5cf9b0ae8f30eebc7b360171bd50f59ab29d39f06a670b3e4501a36ba5897"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b402ddee3d777683de60ff76da801fa7e5e8a71038f57ee53e903afbcefdaa58"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:705832cd7d85605cb7858d8a13d75993c8f3ef1397b0831289109e953d833d29"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:32096b41aaf7a5cc095fa45b4167b890e4c8d3fd217603f3634c92a541de7248"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e769083da9439508833cfc7c23e351e1809e67f47c50248250ce1ac52c21fb93"}, - {file = "ruff-0.8.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5fe716592ae8a376c2673fdfc1f5c0c193a6d0411f90a496863c99cd9e2ae25d"}, - {file = "ruff-0.8.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:81c148825277e737493242b44c5388a300584d73d5774defa9245aaef55448b0"}, - {file = "ruff-0.8.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d261d7850c8367704874847d95febc698a950bf061c9475d4a8b7689adc4f7fa"}, - {file = "ruff-0.8.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:1ca4e3a87496dc07d2427b7dd7ffa88a1e597c28dad65ae6433ecb9f2e4f022f"}, - {file = "ruff-0.8.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:729850feed82ef2440aa27946ab39c18cb4a8889c1128a6d589ffa028ddcfc22"}, - {file = "ruff-0.8.2-py3-none-win32.whl", hash = "sha256:ac42caaa0411d6a7d9594363294416e0e48fc1279e1b0e948391695db2b3d5b1"}, - {file = "ruff-0.8.2-py3-none-win_amd64.whl", hash = "sha256:2aae99ec70abf43372612a838d97bfe77d45146254568d94926e8ed5bbb409ea"}, - {file = "ruff-0.8.2-py3-none-win_arm64.whl", hash = "sha256:fb88e2a506b70cfbc2de6fae6681c4f944f7dd5f2fe87233a7233d888bad73e8"}, - {file = "ruff-0.8.2.tar.gz", hash = "sha256:b84f4f414dda8ac7f75075c1fa0b905ac0ff25361f42e6d5da681a465e0f78e5"}, + {file = "ruff-0.9.3-py3-none-linux_armv6l.whl", hash = "sha256:7f39b879064c7d9670197d91124a75d118d00b0990586549949aae80cdc16624"}, + {file = "ruff-0.9.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a187171e7c09efa4b4cc30ee5d0d55a8d6c5311b3e1b74ac5cb96cc89bafc43c"}, + {file = "ruff-0.9.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c59ab92f8e92d6725b7ded9d4a31be3ef42688a115c6d3da9457a5bda140e2b4"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2dc153c25e715be41bb228bc651c1e9b1a88d5c6e5ed0194fa0dfea02b026439"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:646909a1e25e0dc28fbc529eab8eb7bb583079628e8cbe738192853dbbe43af5"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5a5a46e09355695fbdbb30ed9889d6cf1c61b77b700a9fafc21b41f097bfbba4"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:c4bb09d2bbb394e3730d0918c00276e79b2de70ec2a5231cd4ebb51a57df9ba1"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:96a87ec31dc1044d8c2da2ebbed1c456d9b561e7d087734336518181b26b3aa5"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9bb7554aca6f842645022fe2d301c264e6925baa708b392867b7a62645304df4"}, + {file = "ruff-0.9.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cabc332b7075a914ecea912cd1f3d4370489c8018f2c945a30bcc934e3bc06a6"}, + {file = "ruff-0.9.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:33866c3cc2a575cbd546f2cd02bdd466fed65118e4365ee538a3deffd6fcb730"}, + {file = "ruff-0.9.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:006e5de2621304c8810bcd2ee101587712fa93b4f955ed0985907a36c427e0c2"}, + {file = "ruff-0.9.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:ba6eea4459dbd6b1be4e6bfc766079fb9b8dd2e5a35aff6baee4d9b1514ea519"}, + {file = "ruff-0.9.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:90230a6b8055ad47d3325e9ee8f8a9ae7e273078a66401ac66df68943ced029b"}, + {file = "ruff-0.9.3-py3-none-win32.whl", hash = "sha256:eabe5eb2c19a42f4808c03b82bd313fc84d4e395133fb3fc1b1516170a31213c"}, + {file = "ruff-0.9.3-py3-none-win_amd64.whl", hash = "sha256:040ceb7f20791dfa0e78b4230ee9dce23da3b64dd5848e40e3bf3ab76468dcf4"}, + {file = "ruff-0.9.3-py3-none-win_arm64.whl", hash = "sha256:800d773f6d4d33b0a3c60e2c6ae8f4c202ea2de056365acfa519aa48acf28e0b"}, + {file = "ruff-0.9.3.tar.gz", hash = "sha256:8293f89985a090ebc3ed1064df31f3b4b56320cdfcec8b60d3295bddb955c22a"}, ] [[package]] @@ -2324,6 +2443,8 @@ version = "3.3.3" description = "Python bindings to FreeDesktop.org Secret Service API" optional = false python-versions = ">=3.6" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and sys_platform == \"linux\" and (python_version <= \"3.11\" or python_version >= \"3.12\")" files = [ {file = "SecretStorage-3.3.3-py3-none-any.whl", hash = "sha256:f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99"}, {file = "SecretStorage-3.3.3.tar.gz", hash = "sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77"}, @@ -2339,6 +2460,8 @@ 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.1-py3-none-any.whl", hash = "sha256:4238847e45e24e4472cfcf3554427512c7aab9443396435b1623ef406fff1cc1"}, {file = "selenium-4.28.1.tar.gz", hash = "sha256:0072d08670d7ec32db901bd0107695a330cecac9f196e3afb3fa8163026e022a"}, @@ -2358,6 +2481,8 @@ version = "75.8.0" description = "Easily download, build, install, upgrade, and uninstall Python packages" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "setuptools-75.8.0-py3-none-any.whl", hash = "sha256:e3982f444617239225d675215d51f6ba05f845d4eec313da4418fdbb56fb27e3"}, {file = "setuptools-75.8.0.tar.gz", hash = "sha256:c5afc8f407c626b8313a86e10311dd3f661c6cd9c09d4bf8c15c0e11f9f2b0e6"}, @@ -2378,6 +2503,8 @@ version = "1.5.4" description = "Tool to Detect Surrounding Shell" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686"}, {file = "shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de"}, @@ -2389,6 +2516,8 @@ version = "1.1.0" description = "Simple WebSocket server and client for Python" optional = false python-versions = ">=3.6" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "simple_websocket-1.1.0-py3-none-any.whl", hash = "sha256:4af6069630a38ed6c561010f0e11a5bc0d4ca569b36306eb257cd9a192497c8c"}, {file = "simple_websocket-1.1.0.tar.gz", hash = "sha256:7939234e7aa067c534abdab3a9ed933ec9ce4691b0713c78acb195560aa52ae4"}, @@ -2407,6 +2536,8 @@ version = "1.17.0" description = "Python 2 and 3 compatibility utilities" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" +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"}, {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, @@ -2418,6 +2549,8 @@ version = "1.3.1" description = "Sniff out which async library your code is running under" optional = false python-versions = ">=3.7" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2"}, {file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"}, @@ -2429,6 +2562,8 @@ version = "2.4.0" description = "Sorted Containers -- Sorted List, Sorted Dict, Sorted Set" optional = false python-versions = "*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0"}, {file = "sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88"}, @@ -2440,6 +2575,8 @@ version = "2.0.37" description = "Database Abstraction Library" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "SQLAlchemy-2.0.37-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:da36c3b0e891808a7542c5c89f224520b9a16c7f5e4d6a1156955605e54aef0e"}, {file = "SQLAlchemy-2.0.37-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e7402ff96e2b073a98ef6d6142796426d705addd27b9d26c3b32dbaa06d7d069"}, @@ -2535,6 +2672,8 @@ version = "0.0.22" description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "sqlmodel-0.0.22-py3-none-any.whl", hash = "sha256:a1ed13e28a1f4057cbf4ff6cdb4fc09e85702621d3259ba17b3c230bfb2f941b"}, {file = "sqlmodel-0.0.22.tar.gz", hash = "sha256:7d37c882a30c43464d143e35e9ecaf945d88035e20117bf5ec2834a23cbe505e"}, @@ -2546,18 +2685,19 @@ SQLAlchemy = ">=2.0.14,<2.1.0" [[package]] name = "starlette" -version = "0.45.2" +version = "0.45.3" description = "The little ASGI library that shines." optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ - {file = "starlette-0.45.2-py3-none-any.whl", hash = "sha256:4daec3356fb0cb1e723a5235e5beaf375d2259af27532958e2d79df549dad9da"}, - {file = "starlette-0.45.2.tar.gz", hash = "sha256:bba1831d15ae5212b22feab2f218bab6ed3cd0fc2dc1d4442443bb1ee52260e0"}, + {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.6.2,<5" -typing-extensions = {version = ">=3.10.0", markers = "python_version < \"3.10\""} [package.extras] full = ["httpx (>=0.27.0,<0.29.0)", "itsdangerous", "jinja2", "python-multipart (>=0.0.18)", "pyyaml"] @@ -2568,6 +2708,8 @@ version = "0.14.1" description = "Fast, beautiful and extensible administrative interface framework for Starlette/FastApi applications" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "starlette_admin-0.14.1-py3-none-any.whl", hash = "sha256:5b6260d7ed3db455585852d669feb7ed9a8c5f9a1e3d48d21a52912ec37e18f9"}, {file = "starlette_admin-0.14.1.tar.gz", hash = "sha256:45e2baa3b9a8deec7a6e8ca9295123f648bb0d2070abe68f27193c6d5e32cc38"}, @@ -2591,6 +2733,8 @@ version = "0.9.0" description = "Pretty-print tabular data" optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "tabulate-0.9.0-py3-none-any.whl", hash = "sha256:024ca478df22e9340661486f85298cff5f6dcdba14f3813e8830015b9ed1948f"}, {file = "tabulate-0.9.0.tar.gz", hash = "sha256:0095b12bf5966de529c0feb1fa08671671b3368eec77d7ef7ab114be2c068b3c"}, @@ -2605,6 +2749,8 @@ version = "9.0.0" description = "Retry code until it succeeds" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "tenacity-9.0.0-py3-none-any.whl", hash = "sha256:93de0c98785b27fcf659856aa9f54bfbd399e29969b0621bc7f762bd441b4539"}, {file = "tenacity-9.0.0.tar.gz", hash = "sha256:807f37ca97d62aa361264d497b0e31e92b8027044942bfa756160d908320d73b"}, @@ -2620,6 +2766,8 @@ version = "1.3" description = "The most basic Text::Unidecode port" optional = false python-versions = "*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "text-unidecode-1.3.tar.gz", hash = "sha256:bad6603bb14d279193107714b288be206cac565dfa49aa5b105294dd5c4aab93"}, {file = "text_unidecode-1.3-py2.py3-none-any.whl", hash = "sha256:1311f10e8b895935241623731c2ba64f4c455287888b18189350b67134a822e8"}, @@ -2631,6 +2779,8 @@ version = "0.10.2" description = "Python Library for Tom's Obvious, Minimal Language" optional = false python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, @@ -2642,6 +2792,8 @@ version = "2.2.1" description = "A lil' TOML parser" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version < \"3.11\"" files = [ {file = "tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249"}, {file = "tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6"}, @@ -2683,6 +2835,8 @@ version = "0.13.2" description = "Style preserving TOML library" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "tomlkit-0.13.2-py3-none-any.whl", hash = "sha256:7a974427f6e119197f670fbbbeae7bef749a6c14e793db934baefc1b5f03efde"}, {file = "tomlkit-0.13.2.tar.gz", hash = "sha256:fff5fe59a87295b278abd31bec92c15d9bc4a06885ab12bcea52c71119392e79"}, @@ -2694,6 +2848,8 @@ version = "0.28.0" description = "A friendly Python library for async concurrency and I/O" optional = false python-versions = ">=3.9" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "trio-0.28.0-py3-none-any.whl", hash = "sha256:56d58977acc1635735a96581ec70513cc781b8b6decd299c487d3be2a721cd94"}, {file = "trio-0.28.0.tar.gz", hash = "sha256:4e547896fe9e8a5658e54e4c7c5fa1db748cbbbaa7c965e7d40505b928c73c05"}, @@ -2714,6 +2870,8 @@ version = "0.11.1" description = "WebSocket library for Trio" optional = false python-versions = ">=3.7" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "trio-websocket-0.11.1.tar.gz", hash = "sha256:18c11793647703c158b1f6e62de638acada927344d534e3c7628eedcb746839f"}, {file = "trio_websocket-0.11.1-py3-none-any.whl", hash = "sha256:520d046b0d030cf970b8b2b2e00c4c2245b3807853ecd44214acd33d74581638"}, @@ -2730,6 +2888,8 @@ version = "6.1.0" description = "Collection of utilities for publishing packages on PyPI" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "twine-6.1.0-py3-none-any.whl", hash = "sha256:a47f973caf122930bf0fbbf17f80b83bc1602c9ce393c7845f289a3001dc5384"}, {file = "twine-6.1.0.tar.gz", hash = "sha256:be324f6272eff91d07ee93f251edf232fc647935dd585ac003539b42404a8dbd"}, @@ -2737,7 +2897,6 @@ files = [ [package.dependencies] id = "*" -importlib-metadata = {version = ">=3.6", markers = "python_version < \"3.10\""} keyring = {version = ">=15.1", markers = "platform_machine != \"ppc64le\" and platform_machine != \"s390x\""} packaging = ">=24.0" readme-renderer = ">=35.0" @@ -2756,6 +2915,8 @@ version = "0.15.1" description = "Typer, build great CLIs. Easy to code. Based on Python type hints." optional = false python-versions = ">=3.7" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "typer-0.15.1-py3-none-any.whl", hash = "sha256:7994fb7b8155b64d3402518560648446072864beefd44aa2dc36972a5972e847"}, {file = "typer-0.15.1.tar.gz", hash = "sha256:a0588c0a7fa68a1978a069818657778f86abe6ff5ea6abf472f940a08bfe4f0a"}, @@ -2773,6 +2934,8 @@ version = "4.12.2" description = "Backported and Experimental Type Hints for Python 3.8+" optional = false python-versions = ">=3.8" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"}, {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"}, @@ -2784,6 +2947,8 @@ version = "2025.1" description = "Provider of IANA time zone data" optional = false python-versions = ">=2" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "tzdata-2025.1-py2.py3-none-any.whl", hash = "sha256:7e127113816800496f027041c570f50bcd464a020098a3b6b199517772303639"}, {file = "tzdata-2025.1.tar.gz", hash = "sha256:24894909e88cdb28bd1636c6887801df64cb485bd593f2fd83ef29075a81d694"}, @@ -2795,6 +2960,8 @@ version = "2.3.0" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false python-versions = ">=3.9" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "urllib3-2.3.0-py3-none-any.whl", hash = "sha256:1cee9ad369867bfdbbb48b7dd50374c0967a0bb7710050facf0dd6911440e3df"}, {file = "urllib3-2.3.0.tar.gz", hash = "sha256:f8c5449b3cf0861679ce7e0503c7b44b5ec981bec0d1d3795a07f1ba96f0204d"}, @@ -2815,6 +2982,8 @@ version = "0.34.0" description = "The lightning-fast ASGI server." optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "uvicorn-0.34.0-py3-none-any.whl", hash = "sha256:023dc038422502fa28a09c7a30bf2b6991512da7dcdb8fd35fe57cfc154126f4"}, {file = "uvicorn-0.34.0.tar.gz", hash = "sha256:404051050cd7e905de2c9a7e61790943440b3416f49cb409f965d9dcd0fa73e9"}, @@ -2834,6 +3003,8 @@ version = "20.29.1" description = "Virtual Python Environment builder" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "virtualenv-20.29.1-py3-none-any.whl", hash = "sha256:4e4cb403c0b0da39e13b46b1b2476e505cb0046b25f242bee80f62bf990b2779"}, {file = "virtualenv-20.29.1.tar.gz", hash = "sha256:b8b8970138d32fb606192cb97f6cd4bb644fa486be9308fb9b63f81091b5dc35"}, @@ -2854,6 +3025,8 @@ version = "1.8.0" description = "WebSocket client for Python with low level API options" optional = false python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "websocket_client-1.8.0-py3-none-any.whl", hash = "sha256:17b44cc997f5c498e809b22cdf2d9c7a9e71c02c8cc2b6c56e7c2d1239bfa526"}, {file = "websocket_client-1.8.0.tar.gz", hash = "sha256:3239df9f44da632f96012472805d40a23281a991027ce11d2f45a6f24ac4c3da"}, @@ -2864,90 +3037,14 @@ 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" -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" description = "A built-package format for Python" optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "wheel-0.45.1-py3-none-any.whl", hash = "sha256:708e7481cc80179af0e556bbf0cc00b8444c7321e2700b8d8580231d13017248"}, {file = "wheel-0.45.1.tar.gz", hash = "sha256:661e1abd9198507b1409a20c02106d9670b2576e916d58f520316666abca6729"}, @@ -2962,6 +3059,8 @@ version = "1.17.2" description = "Module for decorators, wrappers and monkey patching." optional = false python-versions = ">=3.8" +groups = ["main"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3d57c572081fed831ad2d26fd430d565b76aa277ed1d30ff4d40670b1c0dd984"}, {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b5e251054542ae57ac7f3fba5d10bfff615b6c2fb09abeb37d2f1463f841ae22"}, @@ -3050,6 +3149,8 @@ version = "1.2.0" description = "WebSockets state-machine based protocol implementation" optional = false python-versions = ">=3.7.0" +groups = ["main", "dev"] +markers = "python_version <= \"3.11\" or python_version >= \"3.12\"" files = [ {file = "wsproto-1.2.0-py3-none-any.whl", hash = "sha256:b9acddd652b585d75b20477888c56642fdade28bdfd3579aa24a4d2c037dd736"}, {file = "wsproto-1.2.0.tar.gz", hash = "sha256:ad565f26ecb92588a3e43bc3d96164de84cd9902482b130d0ddbaa9664a85065"}, @@ -3064,6 +3165,8 @@ version = "3.21.0" description = "Backport of pathlib-compatible object wrapper for zip files" optional = false python-versions = ">=3.9" +groups = ["main"] +markers = "(platform_machine != \"ppc64le\" and platform_machine != \"s390x\") and python_version <= \"3.11\" or python_full_version < \"3.10.2\"" files = [ {file = "zipp-3.21.0-py3-none-any.whl", hash = "sha256:ac1bbe05fd2991f160ebce24ffbac5f6d11d83dc90891255885223d42b3cd931"}, {file = "zipp-3.21.0.tar.gz", hash = "sha256:2c9958f6430a2040341a52eb608ed6dd93ef4392e02ffe219417c1b28b5dd1f4"}, @@ -3078,6 +3181,6 @@ test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools", type = ["pytest-mypy"] [metadata] -lock-version = "2.0" -python-versions = "^3.9" -content-hash = "6965a58abf8d19e9d5833803072a5dd28aaf61b16652918c1b78b4df71147ef4" +lock-version = "2.1" +python-versions = ">=3.10, <4.0" +content-hash = "3b7e6e6e872c68f951f191d85a7d76fe1dd86caf32e2143a53a3152a3686fc7f" diff --git a/pyproject.toml b/pyproject.toml index b6b8aa717..2b5507a1d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ keywords = ["web", "framework"] classifiers = ["Development Status :: 4 - Beta"] [tool.poetry.dependencies] -python = "^3.9" +python = ">=3.10, <4.0" fastapi = ">=0.96.0,!=0.111.0,!=0.111.1" gunicorn = ">=20.1.0,<24.0" jinja2 = ">=3.1.2,<4.0" @@ -50,19 +50,18 @@ httpx = ">=0.25.1,<1.0" twine = ">=4.0.0,<7.0" tomlkit = ">=0.12.4,<1.0" lazy_loader = ">=0.4" -reflex-chakra = ">=0.6.0" 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" pytest-asyncio = ">=0.24.0" pytest-cov = ">=4.0.0,<7.0" -ruff = "0.8.2" +ruff = "0.9.3" pandas = ">=2.1.1,<3.0" pillow = ">=10.0.0,<12.0" plotly = ">=5.13.0,<6.0" @@ -72,6 +71,7 @@ selenium = ">=4.11.0,<5.0" pytest-benchmark = ">=4.0.0,<6.0" playwright = ">=1.46.0" pytest-playwright = ">=0.5.1" +pytest-codspeed = "^3.1.2" [tool.poetry.scripts] reflex = "reflex.reflex:cli" @@ -81,20 +81,24 @@ requires = ["poetry-core>=1.5.1"] build-backend = "poetry.core.masonry.api" [tool.pyright] +reportIncompatibleMethodOverride = false [tool.ruff] -target-version = "py39" +target-version = "py310" output-format = "concise" lint.isort.split-on-trailing-comma = false -lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "T", "W"] -lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"] +lint.select = ["ANN001","B", "C4", "D", "E", "ERA", "F", "FURB", "I", "N", "PERF", "PGH", "PTH", "RUF", "SIM", "T", "TRY", "W"] +lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF008", "RUF012", "TRY0"] lint.pydocstyle.convention = "google" [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] -"tests/*.py" = ["D100", "D103", "D104", "B018", "PERF", "T"] +"tests/*.py" = ["ANN001", "D100", "D103", "D104", "B018", "PERF", "T", "N"] +"benchmarks/*.py" = ["ANN001", "D100", "D103", "D104", "B018", "PERF", "T", "N"] "reflex/.templates/*.py" = ["D100", "D103", "D104"] -"*.pyi" = ["D301", "D415", "D417", "D418", "E742"] +"*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N", "PGH"] +"pyi_generator.py" = ["N802"] +"reflex/constants/*.py" = ["N"] "*/blank.py" = ["I001"] [tool.pytest.ini_options] @@ -102,5 +106,5 @@ asyncio_default_fixture_loop_scope = "function" asyncio_mode = "auto" [tool.codespell] -skip = "docs/*,*.html,examples/*, *.pyi" +skip = "docs/*,*.html,examples/*, *.pyi, poetry.lock" ignore-words-list = "te, TreeE" diff --git a/reflex/.templates/jinja/custom_components/pyproject.toml.jinja2 b/reflex/.templates/jinja/custom_components/pyproject.toml.jinja2 index a5239f33b..abfd998fd 100644 --- a/reflex/.templates/jinja/custom_components/pyproject.toml.jinja2 +++ b/reflex/.templates/jinja/custom_components/pyproject.toml.jinja2 @@ -8,7 +8,7 @@ version = "0.0.1" description = "Reflex custom component {{ module_name }}" readme = "README.md" license = { text = "Apache-2.0" } -requires-python = ">=3.9" +requires-python = ">=3.10" authors = [{ name = "", email = "YOUREMAIL@domain.com" }] keywords = ["reflex","reflex-custom-components"] diff --git a/reflex/.templates/jinja/web/pages/_app.js.jinja2 b/reflex/.templates/jinja/web/pages/_app.js.jinja2 index 40e31dee6..ee3e24540 100644 --- a/reflex/.templates/jinja/web/pages/_app.js.jinja2 +++ b/reflex/.templates/jinja/web/pages/_app.js.jinja2 @@ -38,13 +38,13 @@ export default function MyApp({ Component, pageProps }) { }, []); return ( - - - - - - - + + + + + + + ); } diff --git a/reflex/.templates/jinja/web/pages/utils.js.jinja2 b/reflex/.templates/jinja/web/pages/utils.js.jinja2 index 624e3bee8..08aeb0d38 100644 --- a/reflex/.templates/jinja/web/pages/utils.js.jinja2 +++ b/reflex/.templates/jinja/web/pages/utils.js.jinja2 @@ -86,11 +86,11 @@ {% for condition in case[:-1] %} case JSON.stringify({{ condition._js_expr }}): {% endfor %} - return {{ case[-1] }}; + return {{ render(case[-1]) }}; break; {% endfor %} default: - return {{ component.default }}; + return {{ render(component.default) }}; break; } })() diff --git a/reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js b/reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js index dd7886c89..823eeea99 100644 --- a/reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js +++ b/reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js @@ -16,10 +16,7 @@ export default function RadixThemesColorModeProvider({ children }) { if (isDevMode) { const lastCompiledTimeInLocalStorage = localStorage.getItem("last_compiled_time"); - if ( - lastCompiledTimeInLocalStorage && - lastCompiledTimeInLocalStorage !== lastCompiledTimeStamp - ) { + if (lastCompiledTimeInLocalStorage !== lastCompiledTimeStamp) { // on app startup, make sure the application color mode is persisted correctly. setTheme(defaultColorMode); localStorage.setItem("last_compiled_time", lastCompiledTimeStamp); diff --git a/reflex/.templates/web/utils/state.js b/reflex/.templates/web/utils/state.js index ec603fd13..2f09ac2de 100644 --- a/reflex/.templates/web/utils/state.js +++ b/reflex/.templates/web/utils/state.js @@ -3,6 +3,7 @@ import axios from "axios"; import io from "socket.io-client"; import JSON5 from "json5"; import env from "$/env.json"; +import reflexEnvironment from "$/reflex.json"; import Cookies from "universal-cookie"; import { useEffect, useRef, useState } from "react"; import Router, { useRouter } from "next/router"; @@ -105,6 +106,18 @@ export const getBackendURL = (url_str) => { return endpoint; }; +/** + * Check if the backend is disabled. + * + * @returns True if the backend is disabled, false otherwise. + */ +export const isBackendDisabled = () => { + const cookie = document.cookie + .split("; ") + .find((row) => row.startsWith("backend-enabled=")); + return cookie !== undefined && cookie.split("=")[1] == "false"; +}; + /** * Determine if any event in the event queue is stateful. * @@ -214,8 +227,8 @@ export const applyEvent = async (event, socket) => { a.href = eval?.( event.payload.url.replace( "getBackendURL(env.UPLOAD)", - `"${getBackendURL(env.UPLOAD)}"` - ) + `"${getBackendURL(env.UPLOAD)}"`, + ), ); } a.download = event.payload.filename; @@ -300,10 +313,7 @@ export const applyEvent = async (event, socket) => { // Send the event to the server. if (socket) { - socket.emit( - "event", - event, - ); + socket.emit("event", event); return true; } @@ -331,7 +341,7 @@ export const applyRestEvent = async (event, socket) => { event.payload.files, event.payload.upload_id, event.payload.on_upload_progress, - socket + socket, ); return false; } @@ -398,7 +408,7 @@ export const connect = async ( dispatch, transports, setConnectErrors, - client_storage = {} + client_storage = {}, ) => { // Get backend URL object from the endpoint. const endpoint = getBackendURL(EVENTURL); @@ -407,6 +417,7 @@ export const connect = async ( socket.current = io(endpoint.href, { path: endpoint["pathname"], transports: transports, + protocols: [reflexEnvironment.version], autoUnref: false, }); // Ensure undefined fields in events are sent as null instead of removed @@ -488,14 +499,14 @@ export const uploadFiles = async ( files, upload_id, on_upload_progress, - socket + socket, ) => { // return if there's no file to upload if (files === undefined || files.length === 0) { return false; } - const upload_ref_name = `__upload_controllers_${upload_id}` + const upload_ref_name = `__upload_controllers_${upload_id}`; if (refs[upload_ref_name]) { console.log("Upload already in progress for ", upload_id); @@ -593,7 +604,7 @@ export const Event = ( name, payload = {}, event_actions = {}, - handler = null + handler = null, ) => { return { name, payload, handler, event_actions }; }; @@ -620,7 +631,7 @@ export const hydrateClientStorage = (client_storage) => { for (const state_key in client_storage.local_storage) { const options = client_storage.local_storage[state_key]; const local_storage_value = localStorage.getItem( - options.name || state_key + options.name || state_key, ); if (local_storage_value !== null) { client_storage_values[state_key] = local_storage_value; @@ -631,7 +642,7 @@ export const hydrateClientStorage = (client_storage) => { for (const state_key in client_storage.session_storage) { const session_options = client_storage.session_storage[state_key]; const session_storage_value = sessionStorage.getItem( - session_options.name || state_key + session_options.name || state_key, ); if (session_storage_value != null) { client_storage_values[state_key] = session_storage_value; @@ -656,7 +667,7 @@ export const hydrateClientStorage = (client_storage) => { const applyClientStorageDelta = (client_storage, delta) => { // find the main state and check for is_hydrated const unqualified_states = Object.keys(delta).filter( - (key) => key.split(".").length === 1 + (key) => key.split(".").length === 1, ); if (unqualified_states.length === 1) { const main_state = delta[unqualified_states[0]]; @@ -690,7 +701,7 @@ const applyClientStorageDelta = (client_storage, delta) => { const session_options = client_storage.session_storage[state_key]; sessionStorage.setItem( session_options.name || state_key, - delta[substate][key] + delta[substate][key], ); } } @@ -710,7 +721,7 @@ const applyClientStorageDelta = (client_storage, delta) => { export const useEventLoop = ( dispatch, initial_events = () => [], - client_storage = {} + client_storage = {}, ) => { const socket = useRef(null); const router = useRouter(); @@ -724,7 +735,7 @@ export const useEventLoop = ( event_actions = events.reduce( (acc, e) => ({ ...acc, ...e.event_actions }), - event_actions ?? {} + event_actions ?? {}, ); const _e = args.filter((o) => o?.preventDefault !== undefined)[0]; @@ -752,7 +763,7 @@ export const useEventLoop = ( debounce( combined_name, () => queueEvents(events, socket), - event_actions.debounce + event_actions.debounce, ); } else { queueEvents(events, socket); @@ -771,7 +782,7 @@ export const useEventLoop = ( query, asPath, }))(router), - })) + })), ); sentHydrate.current = true; } @@ -806,14 +817,10 @@ export const useEventLoop = ( }; }, []); - // Main event loop. + // Handle socket connect/disconnect. useEffect(() => { - // Skip if the router is not ready. - if (!router.isReady) { - return; - } - // only use websockets if state is present - if (Object.keys(initialState).length > 1) { + // only use websockets if state is present and backend is not disabled (reflex cloud). + if (Object.keys(initialState).length > 1 && !isBackendDisabled()) { // Initialize the websocket connection. if (!socket.current) { connect( @@ -821,16 +828,31 @@ export const useEventLoop = ( dispatch, ["websocket"], setConnectErrors, - client_storage + client_storage, ); } - (async () => { - // Process all outstanding events. - while (event_queue.length > 0 && !event_processing) { - await processEvent(socket.current); - } - })(); } + + // Cleanup function. + return () => { + if (socket.current) { + socket.current.disconnect(); + } + }; + }, []); + + // Main event loop. + useEffect(() => { + // Skip if the router is not ready. + if (!router.isReady || isBackendDisabled()) { + return; + } + (async () => { + // Process all outstanding events. + while (event_queue.length > 0 && !event_processing) { + await processEvent(socket.current); + } + })(); }); // localStorage event handling @@ -854,7 +876,7 @@ export const useEventLoop = ( vars[storage_to_state_map[e.key]] = e.newValue; const event = Event( `${state_name}.reflex___state____update_vars_internal_state.update_vars_internal`, - { vars: vars } + { vars: vars }, ); addEvents([event], e); } @@ -947,7 +969,7 @@ export const getRefValues = (refs) => { return refs.map((ref) => ref.current ? ref.current.value || ref.current.getAttribute("aria-valuenow") - : null + : null, ); }; diff --git a/reflex/__init__.py b/reflex/__init__.py index 0be568b1a..3209b505e 100644 --- a/reflex/__init__.py +++ b/reflex/__init__.py @@ -84,6 +84,9 @@ In the example above, you will be able to do `rx.list` from __future__ import annotations +from types import ModuleType +from typing import Any + from reflex.utils import ( compat, # for side-effects lazy_loader, @@ -303,7 +306,6 @@ _MAPPING: dict = { "event": [ "EventChain", "EventHandler", - "background", "call_script", "call_function", "run_script", @@ -366,20 +368,5 @@ getattr, __dir__, __all__ = lazy_loader.attach( ) -def __getattr__(name): - if name == "chakra": - from reflex.utils import console - - console.deprecate( - "rx.chakra", - reason="and moved to a separate package. " - "To continue using Chakra UI components, install the `reflex-chakra` package via `pip install " - "reflex-chakra`.", - deprecation_version="0.6.0", - removal_version="0.7.0", - dedupe=True, - ) - import reflex_chakra as rc - - return rc +def __getattr__(name: ModuleType | Any): return getattr(name) diff --git a/reflex/__init__.pyi b/reflex/__init__.pyi index 6bdfa11a0..5c80269ad 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 @@ -156,7 +156,6 @@ from .constants import Env as Env from .constants.colors import Color as Color from .event import EventChain as EventChain from .event import EventHandler as EventHandler -from .event import background as background from .event import call_function as call_function from .event import call_script as call_script from .event import clear_local_storage as clear_local_storage diff --git a/reflex/app.py b/reflex/app.py index 08cb4314e..247977e7e 100644 --- a/reflex/app.py +++ b/reflex/app.py @@ -27,6 +27,7 @@ from typing import ( Dict, Generic, List, + MutableMapping, Optional, Set, Type, @@ -53,12 +54,17 @@ from reflex.compiler.compiler import ExecutorSafeFunctions, compile_theme from reflex.components.base.app_wrap import AppWrap from reflex.components.base.error_boundary import ErrorBoundary from reflex.components.base.fragment import Fragment +from reflex.components.base.strict_mode import StrictMode from reflex.components.component import ( Component, ComponentStyle, evaluate_style_namespaces, ) -from reflex.components.core.banner import connection_pulser, connection_toaster +from reflex.components.core.banner import ( + backend_disabled, + connection_pulser, + connection_toaster, +) from reflex.components.core.breakpoints import set_breakpoints from reflex.components.core.client_side_routing import ( Default404Page, @@ -145,7 +151,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)) @@ -157,9 +163,12 @@ def default_overlay_component() -> Component: Returns: The default overlay_component, which is a connection_modal. """ + config = get_config() + return Fragment.create( connection_pulser(), connection_toaster(), + *([backend_disabled()] if config.is_reflex_cloud else []), *codespaces.codespaces_auto_redirect(), ) @@ -251,36 +260,36 @@ class App(MiddlewareMixin, LifespanMixin): # Attributes to add to the html root tag of every page. html_custom_attrs: Optional[Dict[str, str]] = None - # A map from a route to an unevaluated page. PRIVATE. - unevaluated_pages: Dict[str, UnevaluatedPage] = dataclasses.field( + # A map from a route to an unevaluated page. + _unevaluated_pages: Dict[str, UnevaluatedPage] = dataclasses.field( default_factory=dict ) - # A map from a page route to the component to render. Users should use `add_page`. PRIVATE. - pages: Dict[str, Component] = dataclasses.field(default_factory=dict) + # A map from a page route to the component to render. Users should use `add_page`. + _pages: Dict[str, Component] = dataclasses.field(default_factory=dict) - # The backend API object. PRIVATE. - api: FastAPI = None # type: ignore + # The backend API object. + _api: FastAPI | None = None - # The state class to use for the app. PRIVATE. - state: Optional[Type[BaseState]] = None + # The state class to use for the app. + _state: Optional[Type[BaseState]] = None # Class to manage many client states. _state_manager: Optional[StateManager] = None - # Mapping from a route to event handlers to trigger when the page loads. PRIVATE. - load_events: Dict[str, List[IndividualEventType[[], Any]]] = dataclasses.field( + # Mapping from a route to event handlers to trigger when the page loads. + _load_events: Dict[str, List[IndividualEventType[[], Any]]] = dataclasses.field( default_factory=dict ) - # Admin dashboard to view and manage the database. PRIVATE. + # Admin dashboard to view and manage the database. admin_dash: Optional[AdminDash] = None - # The async server name space. PRIVATE. - event_namespace: Optional[EventNamespace] = None + # The async server name space. + _event_namespace: Optional[EventNamespace] = None - # Background tasks that are currently running. PRIVATE. - background_tasks: Set[asyncio.Task] = dataclasses.field(default_factory=set) + # Background tasks that are currently running. + _background_tasks: Set[asyncio.Task] = dataclasses.field(default_factory=set) # Frontend Error Handler Function frontend_exception_handler: Callable[[Exception], None] = ( @@ -292,6 +301,24 @@ class App(MiddlewareMixin, LifespanMixin): [Exception], Union[EventSpec, List[EventSpec], None] ] = default_backend_exception_handler + @property + def api(self) -> FastAPI | None: + """Get the backend api. + + Returns: + The backend api. + """ + return self._api + + @property + def event_namespace(self) -> EventNamespace | None: + """Get the event namespace. + + Returns: + The event namespace. + """ + return self._event_namespace + def __post_init__(self): """Initialize the app. @@ -311,7 +338,7 @@ class App(MiddlewareMixin, LifespanMixin): set_breakpoints(self.style.pop("breakpoints")) # Set up the API. - self.api = FastAPI(lifespan=self._run_lifespan_tasks) + self._api = FastAPI(lifespan=self._run_lifespan_tasks) self._add_cors() self._add_default_endpoints() @@ -334,8 +361,8 @@ class App(MiddlewareMixin, LifespanMixin): def _enable_state(self) -> None: """Enable state for the app.""" - if not self.state: - self.state = State + if not self._state: + self._state = State self._setup_state() def _setup_state(self) -> None: @@ -344,13 +371,13 @@ class App(MiddlewareMixin, LifespanMixin): Raises: RuntimeError: If the socket server is invalid. """ - if not self.state: + if not self._state: return config = get_config() # Set up the state manager. - self._state_manager = StateManager.create(state=self.state) + self._state_manager = StateManager.create(state=self._state) # Set up the Socket.IO AsyncServer. if not self.sio: @@ -381,12 +408,42 @@ class App(MiddlewareMixin, LifespanMixin): namespace = config.get_event_namespace() # Create the event namespace and attach the main app. Not related to any paths. - self.event_namespace = EventNamespace(namespace, self) + self._event_namespace = EventNamespace(namespace, self) # Register the event namespace with the socket. self.sio.register_namespace(self.event_namespace) # Mount the socket app with the API. - self.api.mount(str(constants.Endpoint.EVENT), socket_app) + if self.api: + + class HeaderMiddleware: + def __init__(self, app: ASGIApp): + self.app = app + + async def __call__( + self, scope: MutableMapping[str, Any], receive: Any, send: Callable + ): + original_send = send + + async def modified_send(message: dict): + if message["type"] == "websocket.accept": + if scope.get("subprotocols"): + # The following *does* say "subprotocol" instead of "subprotocols", intentionally. + message["subprotocol"] = scope["subprotocols"][0] + + headers = dict(message.get("headers", [])) + header_key = b"sec-websocket-protocol" + if subprotocol := headers.get(header_key): + message["headers"] = [ + *message.get("headers", []), + (header_key, subprotocol), + ] + + return await original_send(message) + + return await self.app(scope, receive, modified_send) + + socket_app_with_headers = HeaderMiddleware(socket_app) + self.api.mount(str(constants.Endpoint.EVENT), socket_app_with_headers) # Check the exception handlers self._validate_exception_handlers() @@ -397,24 +454,35 @@ class App(MiddlewareMixin, LifespanMixin): Returns: The string representation of the app. """ - return f"" + return f"" def __call__(self) -> FastAPI: """Run the backend api instance. + Raises: + ValueError: If the app has not been initialized. + Returns: The backend api. """ + if not self.api: + raise ValueError("The app has not been initialized.") return self.api def _add_default_endpoints(self): """Add default api endpoints (ping).""" # To test the server. + if not self.api: + return + self.api.get(str(constants.Endpoint.PING))(ping) self.api.get(str(constants.Endpoint.HEALTH))(health) def _add_optional_endpoints(self): """Add optional api endpoints (_upload).""" + if not self.api: + return + if Upload.is_used: # To upload files. self.api.post(str(constants.Endpoint.UPLOAD))(upload(self)) @@ -432,6 +500,8 @@ class App(MiddlewareMixin, LifespanMixin): def _add_cors(self): """Add CORS middleware to the app.""" + if not self.api: + return self.api.add_middleware( cors.CORSMiddleware, allow_credentials=True, @@ -463,14 +533,8 @@ class App(MiddlewareMixin, LifespanMixin): Returns: The generated component. - - Raises: - exceptions.MatchTypeError: If the return types of match cases in rx.match are different. """ - try: - return component if isinstance(component, Component) else component() - except exceptions.MatchTypeError: - raise + return component if isinstance(component, Component) else component() def add_page( self, @@ -527,13 +591,13 @@ class App(MiddlewareMixin, LifespanMixin): # Check if the route given is valid verify_route_validity(route) - if route in self.unevaluated_pages and environment.RELOAD_CONFIG.is_set(): + if route in self._unevaluated_pages and environment.RELOAD_CONFIG.is_set(): # when the app is reloaded(typically for app harness tests), we should maintain # the latest render function of a route.This applies typically to decorated pages # since they are only added when app._compile is called. - self.unevaluated_pages.pop(route) + self._unevaluated_pages.pop(route) - if route in self.unevaluated_pages: + if route in self._unevaluated_pages: route_name = ( f"`{route}` or `/`" if route == constants.PageNames.INDEX_ROUTE @@ -546,15 +610,15 @@ class App(MiddlewareMixin, LifespanMixin): # Setup dynamic args for the route. # this state assignment is only required for tests using the deprecated state kwarg for App - state = self.state if self.state else State + state = self._state if self._state else State state.setup_dynamic_args(get_route_args(route)) if on_load: - self.load_events[route] = ( + self._load_events[route] = ( on_load if isinstance(on_load, list) else [on_load] ) - self.unevaluated_pages[route] = UnevaluatedPage( + self._unevaluated_pages[route] = UnevaluatedPage( component=component, route=route, title=title, @@ -564,14 +628,15 @@ class App(MiddlewareMixin, LifespanMixin): meta=meta, ) - def _compile_page(self, route: str): + def _compile_page(self, route: str, save_page: bool = True): """Compile a page. Args: route: The route of the page to compile. + save_page: If True, the compiled page is saved to self._pages. """ component, enable_state = compiler.compile_unevaluated_page( - route, self.unevaluated_pages[route], self.state, self.style, self.theme + route, self._unevaluated_pages[route], self._state, self.style, self.theme ) if enable_state: @@ -579,7 +644,8 @@ class App(MiddlewareMixin, LifespanMixin): # Add the page. self._check_routes_conflict(route) - self.pages[route] = component + if save_page: + self._pages[route] = component def get_load_events(self, route: str) -> list[IndividualEventType[[], Any]]: """Get the load events for a route. @@ -593,7 +659,7 @@ class App(MiddlewareMixin, LifespanMixin): route = route.lstrip("/") if route == "": route = constants.PageNames.INDEX_ROUTE - return self.load_events.get(route, []) + return self._load_events.get(route, []) def _check_routes_conflict(self, new_route: str): """Verify if there is any conflict between the new route and any existing route. @@ -617,10 +683,13 @@ class App(MiddlewareMixin, LifespanMixin): constants.RouteRegex.SINGLE_CATCHALL_SEGMENT, constants.RouteRegex.DOUBLE_CATCHALL_SEGMENT, ) - for route in self.pages: + for route in self._pages: replaced_route = replace_brackets_with_keywords(route) for rw, r, nr in zip( - replaced_route.split("/"), route.split("/"), new_route.split("/") + replaced_route.split("/"), + route.split("/"), + new_route.split("/"), + strict=False, ): if rw in segments and r != nr: # If the slugs in the segments of both routes are not the same, then the route is invalid @@ -651,8 +720,8 @@ class App(MiddlewareMixin, LifespanMixin): Args: component: The component to display at the page. title: The title of the page. - description: The description of the page. image: The image to display on the page. + description: The description of the page. on_load: The event handler(s) that will be called each time the page load. meta: The metadata of the page. """ @@ -675,6 +744,9 @@ class App(MiddlewareMixin, LifespanMixin): def _setup_admin_dash(self): """Setup the admin dash.""" # Get the admin dash. + if not self.api: + return + admin_dash = self.admin_dash if admin_dash and admin_dash.models: @@ -716,7 +788,7 @@ class App(MiddlewareMixin, LifespanMixin): 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`" ) @@ -779,10 +851,10 @@ class App(MiddlewareMixin, LifespanMixin): def _setup_overlay_component(self): """If a State is not used and no overlay_component is specified, do not render the connection modal.""" - if self.state is None and self.overlay_component is default_overlay_component: + if self._state is None and self.overlay_component is default_overlay_component: self.overlay_component = None - for k, component in self.pages.items(): - self.pages[k] = self._add_overlay_to_component(component) + for k, component in self._pages.items(): + self._pages[k] = self._add_overlay_to_component(component) def _add_error_boundary_to_component(self, component: Component) -> Component: if self.error_boundary is None: @@ -794,14 +866,14 @@ class App(MiddlewareMixin, LifespanMixin): def _setup_error_boundary(self): """If a State is not used and no error_boundary is specified, do not render the error boundary.""" - if self.state is None and self.error_boundary is default_error_boundary: + if self._state is None and self.error_boundary is default_error_boundary: self.error_boundary = None - for k, component in self.pages.items(): + for k, component in self._pages.items(): # Skip the 404 page if k == constants.Page404.SLUG: continue - self.pages[k] = self._add_error_boundary_to_component(component) + self._pages[k] = self._add_error_boundary_to_component(component) def _apply_decorated_pages(self): """Add @rx.page decorated pages to the app. @@ -827,21 +899,27 @@ class App(MiddlewareMixin, LifespanMixin): Raises: VarDependencyError: When a computed var has an invalid dependency. """ - if not self.state: + if not self._state: return if not state: - state = self.state + state = self._state for var in state.computed_vars.values(): if not var._cache: continue deps = var._deps(objclass=state) - for dep in deps: - if dep not in state.vars and dep not in state.backend_vars: - raise exceptions.VarDependencyError( - f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {dep}" - ) + for state_name, dep_set in deps.items(): + state_cls = ( + state.get_root_state().get_class_substate(state_name) + if state_name != state.get_full_name() + else state + ) + for dep in dep_set: + if dep not in state_cls.vars and dep not in state_cls.backend_vars: + raise exceptions.VarDependencyError( + f"ComputedVar {var._js_expr} on state {state.__name__} has an invalid dependency {state_name}.{dep}" + ) for substate in state.class_subclasses: self._validate_var_dependencies(substate) @@ -857,13 +935,13 @@ class App(MiddlewareMixin, LifespanMixin): """ from reflex.utils.exceptions import ReflexRuntimeError - self.pages = {} + self._pages = {} def get_compilation_time() -> str: return str(datetime.now().time()).split(".")[0] # Render a default 404 page if the user didn't supply one - if constants.Page404.SLUG not in self.unevaluated_pages: + if constants.Page404.SLUG not in self._unevaluated_pages: self.add_page(route=constants.Page404.SLUG) # Fix up the style. @@ -879,20 +957,24 @@ class App(MiddlewareMixin, LifespanMixin): # If a theme component was provided, wrap the app with it app_wrappers[(20, "Theme")] = self.theme - for route in self.unevaluated_pages: - console.debug(f"Evaluating page: {route}") - self._compile_page(route) + # Get the env mode. + config = get_config() - # Add the optional endpoints (_upload) - self._add_optional_endpoints() + if config.react_strict_mode: + app_wrappers[(200, "StrictMode")] = StrictMode.create() + + should_compile = self._should_compile() + + if not should_compile: + for route in self._unevaluated_pages: + console.debug(f"Evaluating page: {route}") + self._compile_page(route, save_page=should_compile) + + # Add the optional endpoints (_upload) + self._add_optional_endpoints() - if not self._should_compile(): return - self._validate_var_dependencies() - self._setup_overlay_component() - self._setup_error_boundary() - # Create a progress bar. progress = Progress( *Progress.get_default_columns()[:-1], @@ -901,18 +983,30 @@ class App(MiddlewareMixin, LifespanMixin): ) # try to be somewhat accurate - but still not 100% - adhoc_steps_without_executor = 6 + adhoc_steps_without_executor = 7 fixed_pages_within_executor = 5 progress.start() task = progress.add_task( f"[{get_compilation_time()}] Compiling:", - total=len(self.pages) + total=len(self._pages) + + (len(self._unevaluated_pages) * 2) + fixed_pages_within_executor + adhoc_steps_without_executor, ) - # Get the env mode. - config = get_config() + for route in self._unevaluated_pages: + console.debug(f"Evaluating page: {route}") + self._compile_page(route, save_page=should_compile) + progress.advance(task) + + # Add the optional endpoints (_upload) + self._add_optional_endpoints() + + self._validate_var_dependencies() + self._setup_overlay_component() + self._setup_error_boundary() + + progress.advance(task) # Store the compile results. compile_results = [] @@ -925,7 +1019,7 @@ class App(MiddlewareMixin, LifespanMixin): # This has to happen before compiling stateful components as that # prevents recursive functions from reaching all components. - for component in self.pages.values(): + for component in self._pages.values(): # Add component._get_all_imports() to all_imports. all_imports.update(component._get_all_imports()) @@ -940,12 +1034,12 @@ class App(MiddlewareMixin, LifespanMixin): stateful_components_path, stateful_components_code, page_components, - ) = compiler.compile_stateful_components(self.pages.values()) + ) = compiler.compile_stateful_components(self._pages.values()) progress.advance(task) # Catch "static" apps (that do not define a rx.State subclass) which are trying to access rx.State. - if code_uses_state_contexts(stateful_components_code) and self.state is None: + if code_uses_state_contexts(stateful_components_code) and self._state is None: raise ReflexRuntimeError( "To access rx.State in frontend components, at least one " "subclass of rx.State must be defined in the app." @@ -959,7 +1053,7 @@ class App(MiddlewareMixin, LifespanMixin): 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] ) ) @@ -982,20 +1076,20 @@ class App(MiddlewareMixin, LifespanMixin): max_workers=environment.REFLEX_COMPILE_THREADS.get() or None ) - for route, component in zip(self.pages, page_components): + for route, component in zip(self._pages, page_components, strict=True): ExecutorSafeFunctions.COMPONENTS[route] = component - ExecutorSafeFunctions.STATE = self.state + ExecutorSafeFunctions.STATE = self._state with executor: result_futures = [] - def _submit_work(fn, *args, **kwargs): + def _submit_work(fn: Callable, *args, **kwargs): f = executor.submit(fn, *args, **kwargs) result_futures.append(f) # Compile the pre-compiled pages. - for route in self.pages: + for route in self._pages: _submit_work( ExecutorSafeFunctions.compile_page, route, @@ -1030,7 +1124,7 @@ class App(MiddlewareMixin, LifespanMixin): # Compile the contexts. compile_results.append( - compiler.compile_contexts(self.state, self.theme), + compiler.compile_contexts(self._state, self.theme), ) if self.theme is not None: # Fix #2992 by removing the top-level appearance prop @@ -1152,9 +1246,9 @@ class App(MiddlewareMixin, LifespanMixin): ) task = asyncio.create_task(_coro()) - self.background_tasks.add(task) + self._background_tasks.add(task) # Clean up task from background_tasks set when complete. - task.add_done_callback(self.background_tasks.discard) + task.add_done_callback(self._background_tasks.discard) return task def _validate_exception_handlers(self): @@ -1164,11 +1258,11 @@ class App(MiddlewareMixin, LifespanMixin): ValueError: If the custom exception handlers are invalid. """ - FRONTEND_ARG_SPEC = { + frontend_arg_spec = { "exception": Exception, } - BACKEND_ARG_SPEC = { + backend_arg_spec = { "exception": Exception, } @@ -1176,9 +1270,10 @@ class App(MiddlewareMixin, LifespanMixin): ["frontend", "backend"], [self.frontend_exception_handler, self.backend_exception_handler], [ - FRONTEND_ARG_SPEC, - BACKEND_ARG_SPEC, + frontend_arg_spec, + backend_arg_spec, ], + strict=True, ): if hasattr(handler_fn, "__name__"): _fn_name = handler_fn.__name__ @@ -1219,7 +1314,7 @@ class App(MiddlewareMixin, LifespanMixin): ): raise ValueError( f"Provided custom {handler_domain} exception handler `{_fn_name}` has the wrong argument order." - f"Expected `{required_arg}` as the {required_arg_index+1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`" + f"Expected `{required_arg}` as the {required_arg_index + 1} argument but got `{list(arg_annotations.keys())[required_arg_index]}`" ) if not issubclass(arg_annotations[required_arg], Exception): @@ -1320,15 +1415,14 @@ async def process( if app._process_background(state, event) is not None: # `final=True` allows the frontend send more events immediately. yield StateUpdate(final=True) - return + else: + # Process the event synchronously. + async for update in state._process(event): + # Postprocess the event. + update = await app._postprocess(state, event, update) - # Process the event synchronously. - async for update in state._process(event): - # Postprocess the event. - update = await app._postprocess(state, event, update) - - # Yield the update. - yield update + # Yield the update. + yield update except Exception as ex: telemetry.send_error(ex, context="backend") @@ -1523,16 +1617,20 @@ class EventNamespace(AsyncNamespace): self.sid_to_token = {} self.app = app - def on_connect(self, sid, environ): + def on_connect(self, sid: str, environ: dict): """Event for when the websocket is connected. Args: sid: The Socket.IO session id. environ: The request information, including HTTP headers. """ - pass + subprotocol = environ.get("HTTP_SEC_WEBSOCKET_PROTOCOL") + if subprotocol and subprotocol != constants.Reflex.VERSION: + console.warn( + f"Frontend version {subprotocol} for session {sid} does not match the backend version {constants.Reflex.VERSION}." + ) - def on_disconnect(self, sid): + def on_disconnect(self, sid: str): """Event for when the websocket disconnects. Args: @@ -1554,7 +1652,7 @@ class EventNamespace(AsyncNamespace): self.emit(str(constants.SocketEvent.EVENT), update, to=sid) ) - async def on_event(self, sid, data): + async def on_event(self, sid: str, data: Any): """Event for receiving front-end websocket events. Raises: @@ -1563,10 +1661,36 @@ class EventNamespace(AsyncNamespace): Args: sid: The Socket.IO session id. data: The event data. + + Raises: + EventDeserializationError: If the event data is not a dictionary. """ fields = data - # Get the event. - event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS}) + + if isinstance(fields, str): + console.warn( + "Received event data as a string. This generally should not happen and may indicate a bug." + f" Event data: {fields}" + ) + try: + fields = json.loads(fields) + except json.JSONDecodeError as ex: + raise exceptions.EventDeserializationError( + f"Failed to deserialize event data: {fields}." + ) from ex + + if not isinstance(fields, dict): + raise exceptions.EventDeserializationError( + f"Event data must be a dictionary, but received {fields} of type {type(fields)}." + ) + + try: + # Get the event. + event = Event(**{k: v for k, v in fields.items() if k in _EVENT_FIELDS}) + except (TypeError, ValueError) as ex: + raise exceptions.EventDeserializationError( + f"Failed to deserialize event data: {fields}." + ) from ex self.token_to_sid[event.token] = sid self.sid_to_token[sid] = event.token @@ -1595,7 +1719,7 @@ class EventNamespace(AsyncNamespace): # Emit the update from processing the event. await self.emit_update(update=update, sid=sid) - async def on_ping(self, sid): + async def on_ping(self, sid: str): """Event for testing the API endpoint. Args: diff --git a/reflex/app_mixins/lifespan.py b/reflex/app_mixins/lifespan.py index 52bf0be1d..50b90f25c 100644 --- a/reflex/app_mixins/lifespan.py +++ b/reflex/app_mixins/lifespan.py @@ -12,7 +12,7 @@ from typing import Callable, Coroutine, Set, Union from fastapi import FastAPI from reflex.utils import console -from reflex.utils.exceptions import InvalidLifespanTaskType +from reflex.utils.exceptions import InvalidLifespanTaskTypeError from .mixin import AppMixin @@ -32,7 +32,7 @@ class LifespanMixin(AppMixin): 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: @@ -61,19 +61,19 @@ class LifespanMixin(AppMixin): Args: task: The task to register. - task_kwargs: The kwargs of the task. + **task_kwargs: The kwargs of the task. Raises: - InvalidLifespanTaskType: If the task is a generator function. + InvalidLifespanTaskTypeError: If the task is a generator function. """ if inspect.isgeneratorfunction(task) or inspect.isasyncgenfunction(task): - raise InvalidLifespanTaskType( + raise InvalidLifespanTaskTypeError( f"Task {task.__name__} of type generator must be decorated with contextlib.asynccontextmanager." ) 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 30593d9ae..c81fd7806 100644 --- a/reflex/app_mixins/middleware.py +++ b/reflex/app_mixins/middleware.py @@ -53,11 +53,11 @@ class MiddlewareMixin(AppMixin): """ 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 @@ class MiddlewareMixin(AppMixin): 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/app_module_for_backend.py b/reflex/app_module_for_backend.py index 8109fc3d6..28be30410 100644 --- a/reflex/app_module_for_backend.py +++ b/reflex/app_module_for_backend.py @@ -5,16 +5,13 @@ Only the app attribute is explicitly exposed. from concurrent.futures import ThreadPoolExecutor from reflex import constants -from reflex.utils import telemetry from reflex.utils.exec import is_prod_mode -from reflex.utils.prerequisites import get_app +from reflex.utils.prerequisites import get_and_validate_app if constants.CompileVars.APP != "app": raise AssertionError("unexpected variable name for 'app'") -telemetry.send("compile") -app_module = get_app(reload=False) -app = getattr(app_module, constants.CompileVars.APP) +app, app_module = get_and_validate_app(reload=False) # For py3.9 compatibility when redis is used, we MUST add any decorator pages # before compiling the app in a thread to avoid event loop error (REF-2172). app._apply_decorated_pages() @@ -30,8 +27,7 @@ if is_prod_mode(): # ensure only "app" is exposed. del app_module del compile_future -del get_app +del get_and_validate_app del is_prod_mode -del telemetry del constants del ThreadPoolExecutor diff --git a/reflex/base.py b/reflex/base.py index a88e557ef..f6bbb8ce4 100644 --- a/reflex/base.py +++ b/reflex/base.py @@ -13,7 +13,7 @@ except ModuleNotFoundError: 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,12 +75,12 @@ class Base(BaseModel): # pyright: ignore [reportUnboundVariable] """ from reflex.utils.serializers import serialize - return self.__config__.json_dumps( # type: ignore + return self.__config__.json_dumps( self.dict(), default=serialize, ) - def set(self, **kwargs): + def set(self, **kwargs: Any): """Set multiple fields and return the object. Args: @@ -113,12 +113,12 @@ class Base(BaseModel): # pyright: ignore [reportUnboundVariable] 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/compiler.py b/reflex/compiler/compiler.py index 218dd0c55..c2a76aad3 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -239,11 +239,19 @@ def _compile_components( component_renders.append(component_render) imports = utils.merge_imports(imports, component_imports) + dynamic_imports = { + comp_import: None + for comp_render in component_renders + if "dynamic_imports" in comp_render + for comp_import in comp_render["dynamic_imports"] + } + # Compile the components page. return ( templates.COMPONENTS.render( imports=utils.compile_imports(imports), components=component_renders, + dynamic_imports=dynamic_imports, ), imports, ) diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index c0ba28f4b..57241fea9 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -2,17 +2,24 @@ from __future__ import annotations +import asyncio +import concurrent.futures +import traceback +from datetime import datetime from pathlib import Path from typing import Any, Callable, Dict, Optional, Type, Union from urllib.parse import urlparse +from reflex.utils.exec import is_in_app_harness from reflex.utils.prerequisites import get_web_dir from reflex.vars.base import Var 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 ( @@ -29,7 +36,7 @@ from reflex.components.base import ( ) from reflex.components.component import Component, ComponentStyle, CustomComponent from reflex.istate.storage import Cookie, LocalStorage, SessionStorage -from reflex.state import BaseState +from reflex.state import BaseState, _resolve_delta from reflex.style import Style from reflex.utils import console, format, imports, path_ops from reflex.utils.imports import ImportVar, ParsedImportDict @@ -115,7 +122,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: @@ -163,13 +170,34 @@ def compile_state(state: Type[BaseState]) -> dict: try: initial_state = state(_reflex_internal_init=True).dict(initial=True) except Exception as e: + timestamp = datetime.now().strftime("%Y-%m-%d__%H-%M-%S") + constants.Reflex.LOGS_DIR.mkdir(parents=True, exist_ok=True) + log_path = constants.Reflex.LOGS_DIR / f"state_compile_error_{timestamp}.log" + traceback.TracebackException.from_exception(e).print(file=log_path.open("w+")) console.warn( - f"Failed to compile initial state with computed vars, excluding them: {e}" + f"Failed to compile initial state with computed vars. Error log saved to {log_path}" ) initial_state = state(_reflex_internal_init=True).dict( initial=True, include_computed=False ) - return initial_state + try: + _ = asyncio.get_running_loop() + except RuntimeError: + pass + else: + if is_in_app_harness(): + # Playwright tests already have an event loop running, so we can't use asyncio.run. + with concurrent.futures.ThreadPoolExecutor() as pool: + resolved_initial_state = pool.submit( + asyncio.run, _resolve_delta(initial_state) + ).result() + console.warn( + f"Had to get initial state in a thread 🤮 {resolved_initial_state}", + ) + return resolved_initial_state + + # Normally the compile runs before any event loop starts, we asyncio.run is available for calling. + return asyncio.run(_resolve_delta(initial_state)) def _compile_client_storage_field( @@ -292,6 +320,7 @@ def compile_custom_component( "render": render.render(), "hooks": render._get_all_hooks(), "custom_code": render._get_all_custom_code(), + "dynamic_imports": render._get_all_dynamic_imports(), }, imports, ) @@ -494,7 +523,7 @@ def empty_dir(path: str | Path, keep_files: list[str] | None = None): path_ops.rm(element) -def is_valid_url(url) -> bool: +def is_valid_url(url: str) -> bool: """Check if a url is valid. Args: diff --git a/reflex/components/base/bare.py b/reflex/components/base/bare.py index e576fac85..0f0bef8b9 100644 --- a/reflex/components/base/bare.py +++ b/reflex/components/base/bare.py @@ -31,7 +31,7 @@ class Bare(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/error_boundary.py b/reflex/components/base/error_boundary.py index f328773c2..74867a757 100644 --- a/reflex/components/base/error_boundary.py +++ b/reflex/components/base/error_boundary.py @@ -11,10 +11,11 @@ from reflex.event import EventHandler, set_clipboard from reflex.state import FrontendEventExceptionState from reflex.vars.base import Var from reflex.vars.function import ArgsFunctionOperation +from reflex.vars.object import ObjectVar def on_error_spec( - error: Var[Dict[str, str]], info: Var[Dict[str, str]] + error: ObjectVar[Dict[str, str]], info: ObjectVar[Dict[str, str]] ) -> Tuple[Var[str], Var[str]]: """The spec for the on_error event handler. diff --git a/reflex/components/base/error_boundary.pyi b/reflex/components/base/error_boundary.pyi index 2e01c7da0..8d27af0f3 100644 --- a/reflex/components/base/error_boundary.pyi +++ b/reflex/components/base/error_boundary.pyi @@ -9,9 +9,10 @@ from reflex.components.component import Component from reflex.event import BASE_STATE, EventType from reflex.style import Style from reflex.vars.base import Var +from reflex.vars.object import ObjectVar def on_error_spec( - error: Var[Dict[str, str]], info: Var[Dict[str, str]] + error: ObjectVar[Dict[str, str]], info: ObjectVar[Dict[str, str]] ) -> Tuple[Var[str], Var[str]]: ... class ErrorBoundary(Component): diff --git a/reflex/components/base/meta.py b/reflex/components/base/meta.py index 526233c8b..10264009e 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/base/strict_mode.py b/reflex/components/base/strict_mode.py new file mode 100644 index 000000000..46b01ad87 --- /dev/null +++ b/reflex/components/base/strict_mode.py @@ -0,0 +1,10 @@ +"""Module for the StrictMode component.""" + +from reflex.components.component import Component + + +class StrictMode(Component): + """A React strict mode component to enable strict mode for its children.""" + + library = "react" + tag = "StrictMode" diff --git a/reflex/components/base/strict_mode.pyi b/reflex/components/base/strict_mode.pyi new file mode 100644 index 000000000..9005c0222 --- /dev/null +++ b/reflex/components/base/strict_mode.pyi @@ -0,0 +1,57 @@ +"""Stub file for reflex/components/base/strict_mode.py""" + +# ------------------- DO NOT EDIT ---------------------- +# This file was generated by `reflex/utils/pyi_generator.py`! +# ------------------------------------------------------ +from typing import Any, Dict, Optional, Union, overload + +from reflex.components.component import Component +from reflex.event import BASE_STATE, EventType +from reflex.style import Style +from reflex.vars.base import Var + +class StrictMode(Component): + @overload + @classmethod + def create( # type: ignore + cls, + *children, + style: Optional[Style] = None, + key: Optional[Any] = None, + id: Optional[Any] = None, + class_name: Optional[Any] = None, + autofocus: Optional[bool] = None, + custom_attrs: Optional[Dict[str, Union[Var, Any]]] = None, + on_blur: Optional[EventType[[], BASE_STATE]] = None, + on_click: Optional[EventType[[], BASE_STATE]] = None, + on_context_menu: Optional[EventType[[], BASE_STATE]] = None, + on_double_click: Optional[EventType[[], BASE_STATE]] = None, + on_focus: Optional[EventType[[], BASE_STATE]] = None, + on_mount: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_down: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_enter: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_leave: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_move: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_out: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_over: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_up: Optional[EventType[[], BASE_STATE]] = None, + on_scroll: Optional[EventType[[], BASE_STATE]] = None, + on_unmount: Optional[EventType[[], BASE_STATE]] = None, + **props, + ) -> "StrictMode": + """Create the component. + + Args: + *children: The children of the component. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + class_name: The class name for the component. + autofocus: Whether the component should take the focus once the page is loaded + custom_attrs: custom attribute + **props: The props of the component. + + Returns: + The component. + """ + ... diff --git a/reflex/components/component.py b/reflex/components/component.py index 8649b593d..6d1264f4d 100644 --- a/reflex/components/component.py +++ b/reflex/components/component.py @@ -23,8 +23,6 @@ from typing import ( Union, ) -from typing_extensions import deprecated - import reflex.state from reflex.base import Base from reflex.compiler.templates import STATEFUL_COMPONENT @@ -47,11 +45,10 @@ from reflex.event import ( EventChain, EventHandler, EventSpec, - EventVar, no_args_event_spec, ) from reflex.style import Style, format_as_emotion -from reflex.utils import console, format, imports, types +from reflex.utils import format, imports, types from reflex.utils.imports import ( ImmutableParsedImportDict, ImportDict, @@ -153,7 +150,7 @@ class BaseComponent(Base, ABC): 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: @@ -429,20 +426,22 @@ class Component(BaseComponent, ABC): else: continue + def determine_key(value: Any): + # Try to create a var from the value + key = value if isinstance(value, Var) else LiteralVar.create(value) + + # Check that the var type is not None. + if key is None: + raise TypeError + + return key + # Check whether the key is a component prop. if types._issubclass(field_type, Var): # Used to store the passed types if var type is a union. passed_types = None try: - # Try to create a var from the value. - if isinstance(value, Var): - kwargs[key] = value - else: - kwargs[key] = LiteralVar.create(value) - - # Check that the var type is not None. - if kwargs[key] is None: - raise TypeError + kwargs[key] = determine_key(value) expected_type = fields[key].outer_type_.__args__[0] # validate literal fields. @@ -463,9 +462,7 @@ class Component(BaseComponent, ABC): 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. @@ -492,7 +489,7 @@ class Component(BaseComponent, ABC): # 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, ) @@ -545,41 +542,6 @@ class Component(BaseComponent, ABC): # Construct the component. super().__init__(*args, **kwargs) - @deprecated("Use rx.EventChain.create instead.") - def _create_event_chain( - self, - args_spec: types.ArgsSpec | Sequence[types.ArgsSpec], - value: Union[ - Var, - EventHandler, - EventSpec, - List[Union[EventHandler, EventSpec, EventVar]], - Callable, - ], - key: Optional[str] = None, - ) -> Union[EventChain, Var]: - """Create an event chain from a variety of input types. - - Args: - args_spec: The args_spec of the event trigger being bound. - value: The value to create the event chain from. - key: The key of the event trigger being bound. - - Returns: - The event chain. - """ - console.deprecate( - "Component._create_event_chain", - "Use rx.EventChain.create instead.", - deprecation_version="0.6.8", - removal_version="0.7.0", - ) - return EventChain.create( - value=value, # type: ignore - args_spec=args_spec, - key=key, - ) - def get_event_triggers( self, ) -> Dict[str, types.ArgsSpec | Sequence[types.ArgsSpec]]: @@ -614,7 +576,7 @@ class Component(BaseComponent, ABC): 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: @@ -661,8 +623,7 @@ class Component(BaseComponent, ABC): if props is None: # Add component props to the tag. props = { - attr[:-1] if attr.endswith("_") else attr: getattr(self, attr) - for attr in self.get_props() + attr.removesuffix("_"): getattr(self, attr) for attr in self.get_props() } # Add ref to element if `id` is not None. @@ -740,22 +701,21 @@ class Component(BaseComponent, ABC): # Import here to avoid circular imports. from reflex.components.base.bare import Bare from reflex.components.base.fragment import Fragment - from reflex.utils.exceptions import ComponentTypeError + from reflex.utils.exceptions import ChildrenTypeError # Filter out None props props = {key: value for key, value in props.items() if value is not None} - def validate_children(children): + def validate_children(children: tuple | list): for child in children: - if isinstance(child, tuple): + if isinstance(child, (tuple, list)): validate_children(child) + # Make sure the child is a valid type. - if not types._isinstance(child, ComponentChild): - raise ComponentTypeError( - "Children of Reflex components must be other components, " - "state vars, or primitive Python types. " - f"Got child {child} of type {type(child)}.", - ) + if isinstance(child, dict) or not types._isinstance( + child, ComponentChild + ): + raise ChildrenTypeError(component=cls.__name__, child=child) # Validate all the children. validate_children(children) @@ -798,7 +758,7 @@ class Component(BaseComponent, ABC): # 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) @@ -890,7 +850,7 @@ class Component(BaseComponent, ABC): else {} ) - def render(self) -> Dict: + def render(self) -> dict: """Render the component. Returns: @@ -908,7 +868,7 @@ class Component(BaseComponent, ABC): self._replace_prop_names(rendered_dict) return rendered_dict - def _replace_prop_names(self, rendered_dict) -> None: + def _replace_prop_names(self, rendered_dict: dict) -> None: """Replace the prop names in the render dictionary. Args: @@ -948,7 +908,7 @@ class Component(BaseComponent, ABC): comp.__name__ for comp in (Fragment, Foreach, Cond, Match) ] - def validate_child(child): + def validate_child(child: Any): child_name = type(child).__name__ # Iterate through the immediate children of fragment @@ -1711,7 +1671,7 @@ class CustomComponent(Component): 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(), ) @@ -1744,7 +1704,7 @@ class CustomComponent(Component): 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: @@ -1839,7 +1799,7 @@ class CustomComponent(Component): 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. @@ -1983,7 +1943,7 @@ class StatefulComponent(BaseComponent): if not should_memoize: # Determine if any Vars have associated data. - for prop_var in component._get_vars(): + for prop_var in component._get_vars(include_children=True): if prop_var._get_all_var_data(): should_memoize = True break @@ -2366,8 +2326,8 @@ class MemoizationLeaf(Component): """ comp = super().create(*children, **props) if comp._get_all_hooks(): - comp._memoization_mode = cls._memoization_mode.copy( - update={"disposition": MemoizationDisposition.ALWAYS} + comp._memoization_mode = dataclasses.replace( + comp._memoization_mode, disposition=MemoizationDisposition.ALWAYS ) return comp @@ -2428,7 +2388,7 @@ def render_dict_to_var(tag: dict | Component | str, imported_names: set[str]) -> if tag["name"] == "match": element = tag["cond"] - conditionals = tag["default"] + conditionals = render_dict_to_var(tag["default"], imported_names) for case in tag["match_cases"][::-1]: condition = case[0].to_string() == element.to_string() @@ -2437,7 +2397,7 @@ def render_dict_to_var(tag: dict | Component | str, imported_names: set[str]) -> conditionals = ternary_operation( condition, - case[-1], + render_dict_to_var(case[-1], imported_names), conditionals, ) @@ -2496,6 +2456,7 @@ def render_dict_to_var(tag: dict | Component | str, imported_names: set[str]) -> @dataclasses.dataclass( eq=False, frozen=True, + slots=True, ) class LiteralComponentVar(CachedVarOperation, LiteralVar, ComponentVar): """A Var that represents a Component.""" diff --git a/reflex/components/core/banner.py b/reflex/components/core/banner.py index b7b6fae6c..882975f2f 100644 --- a/reflex/components/core/banner.py +++ b/reflex/components/core/banner.py @@ -4,8 +4,10 @@ from __future__ import annotations from typing import Optional +from reflex import constants from reflex.components.component import Component from reflex.components.core.cond import cond +from reflex.components.datadisplay.logo import svg_logo from reflex.components.el.elements.typography import Div from reflex.components.lucide.icon import Icon from reflex.components.radix.themes.components.dialog import ( @@ -25,7 +27,7 @@ from reflex.vars.function import FunctionStringVar 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 +101,14 @@ class ConnectionToaster(Toaster): """ 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 +118,7 @@ class ConnectionToaster(Toaster): _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( @@ -293,7 +295,84 @@ class ConnectionPulser(Div): ) +class BackendDisabled(Div): + """A component that displays a message when the backend is disabled.""" + + @classmethod + def create(cls, **props) -> Component: + """Create a backend disabled component. + + Args: + **props: The properties of the component. + + Returns: + The backend disabled component. + """ + import reflex as rx + + is_backend_disabled = Var( + "backendDisabled", + _var_type=bool, + _var_data=VarData( + hooks={ + "const [backendDisabled, setBackendDisabled] = useState(false);": None, + "useEffect(() => { setBackendDisabled(isBackendDisabled()); }, []);": None, + }, + imports={ + f"$/{constants.Dirs.STATE_PATH}": [ + ImportVar(tag="isBackendDisabled") + ], + }, + ), + ) + + return super().create( + rx.cond( + is_backend_disabled, + rx.box( + rx.box( + rx.card( + rx.vstack( + svg_logo(), + rx.text( + "You ran out of compute credits.", + ), + rx.callout( + rx.fragment( + "Please upgrade your plan or raise your compute credits at ", + rx.link( + "Reflex Cloud.", + href="https://cloud.reflex.dev/", + ), + ), + width="100%", + icon="info", + variant="surface", + ), + ), + font_size="20px", + font_family='"Inter", "Helvetica", "Arial", sans-serif', + variant="classic", + ), + position="fixed", + top="50%", + left="50%", + transform="translate(-50%, -50%)", + width="40ch", + max_width="90vw", + ), + position="fixed", + z_index=9999, + backdrop_filter="grayscale(1) blur(5px)", + width="100dvw", + height="100dvh", + ), + ) + ) + + connection_banner = ConnectionBanner.create connection_modal = ConnectionModal.create connection_toaster = ConnectionToaster.create connection_pulser = ConnectionPulser.create +backend_disabled = BackendDisabled.create diff --git a/reflex/components/core/banner.pyi b/reflex/components/core/banner.pyi index f44ee7992..2ea514965 100644 --- a/reflex/components/core/banner.pyi +++ b/reflex/components/core/banner.pyi @@ -350,7 +350,93 @@ class ConnectionPulser(Div): """ ... +class BackendDisabled(Div): + @overload + @classmethod + def create( # type: ignore + cls, + *children, + access_key: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + auto_capitalize: Optional[ + Union[Var[Union[bool, int, str]], bool, int, str] + ] = None, + content_editable: Optional[ + Union[Var[Union[bool, int, str]], bool, int, str] + ] = None, + context_menu: Optional[ + Union[Var[Union[bool, int, str]], bool, int, str] + ] = None, + dir: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + draggable: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + enter_key_hint: Optional[ + Union[Var[Union[bool, int, str]], bool, int, str] + ] = None, + hidden: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + input_mode: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + item_prop: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + lang: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + role: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + slot: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + spell_check: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + tab_index: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + title: Optional[Union[Var[Union[bool, int, str]], bool, int, str]] = None, + style: Optional[Style] = None, + key: Optional[Any] = None, + id: Optional[Any] = None, + class_name: Optional[Any] = None, + autofocus: Optional[bool] = None, + custom_attrs: Optional[Dict[str, Union[Var, Any]]] = None, + on_blur: Optional[EventType[[], BASE_STATE]] = None, + on_click: Optional[EventType[[], BASE_STATE]] = None, + on_context_menu: Optional[EventType[[], BASE_STATE]] = None, + on_double_click: Optional[EventType[[], BASE_STATE]] = None, + on_focus: Optional[EventType[[], BASE_STATE]] = None, + on_mount: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_down: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_enter: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_leave: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_move: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_out: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_over: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_up: Optional[EventType[[], BASE_STATE]] = None, + on_scroll: Optional[EventType[[], BASE_STATE]] = None, + on_unmount: Optional[EventType[[], BASE_STATE]] = None, + **props, + ) -> "BackendDisabled": + """Create a backend disabled component. + + Args: + access_key: Provides a hint for generating a keyboard shortcut for the current element. + auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user. + content_editable: Indicates whether the element's content is editable. + context_menu: Defines the ID of a element which will serve as the element's context menu. + dir: Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left) + draggable: Defines whether the element can be dragged. + enter_key_hint: Hints what media types the media element is able to play. + hidden: Defines whether the element is hidden. + input_mode: Defines the type of the element. + item_prop: Defines the name of the element for metadata purposes. + lang: Defines the language used in the element. + role: Defines the role of the element. + slot: Assigns a slot in a shadow DOM shadow tree to an element. + spell_check: Defines whether the element may be checked for spelling errors. + tab_index: Defines the position of the current element in the tabbing order. + title: Defines a tooltip for the element. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + class_name: The class name for the component. + autofocus: Whether the component should take the focus once the page is loaded + custom_attrs: custom attribute + **props: The properties of the component. + + Returns: + The backend disabled component. + """ + ... + connection_banner = ConnectionBanner.create connection_modal = ConnectionModal.create connection_toaster = ConnectionToaster.create connection_pulser = ConnectionPulser.create +backend_disabled = BackendDisabled.create diff --git a/reflex/components/core/breakpoints.py b/reflex/components/core/breakpoints.py index 25396ecd9..9a8ef1556 100644 --- a/reflex/components/core/breakpoints.py +++ b/reflex/components/core/breakpoints.py @@ -82,7 +82,9 @@ class Breakpoints(Dict[K, V]): return Breakpoints( { k: v - for k, v in zip(["initial", *breakpoint_names], thresholds) + for k, v in zip( + ["initial", *breakpoint_names], thresholds, strict=True + ) if v is not None } ) diff --git a/reflex/components/core/client_side_routing.py b/reflex/components/core/client_side_routing.py index a10b90de8..0fc40de5f 100644 --- a/reflex/components/core/client_side_routing.py +++ b/reflex/components/core/client_side_routing.py @@ -41,7 +41,7 @@ class ClientSideRouting(Component): return "" -def wait_for_client_redirect(component) -> Component: +def wait_for_client_redirect(component: Component) -> Component: """Wait for a redirect to occur before rendering a component. This prevents the 404 page from flashing while the redirect is happening. diff --git a/reflex/components/core/client_side_routing.pyi b/reflex/components/core/client_side_routing.pyi index 581b0e120..078698198 100644 --- a/reflex/components/core/client_side_routing.pyi +++ b/reflex/components/core/client_side_routing.pyi @@ -60,7 +60,7 @@ class ClientSideRouting(Component): """ ... -def wait_for_client_redirect(component) -> Component: ... +def wait_for_client_redirect(component: Component) -> Component: ... class Default404Page(Component): @overload diff --git a/reflex/components/core/cond.py b/reflex/components/core/cond.py index 488990f54..6f9110a16 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 @@ class Cond(MemoizationLeaf): 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 @@ class Cond(MemoizationLeaf): @overload -def cond(condition: Any, c1: Component, c2: Any) -> Component: ... +def cond(condition: Any, c1: Component, c2: Any) -> Component: ... # pyright: ignore [reportOverlappingOverload] @overload @@ -154,7 +153,7 @@ def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var: if c2 is None: raise ValueError("For conditional vars, the second argument must be set.") - def create_var(cond_part): + def create_var(cond_part: Any) -> Var[Any]: return LiteralVar.create(cond_part) # convert the truth and false cond parts into vars so the _var_data can be obtained. @@ -163,16 +162,16 @@ def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var: # 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 12cc94426..1d798994d 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/foreach.py b/reflex/components/core/foreach.py index c9fbe5bc5..927b01333 100644 --- a/reflex/components/core/foreach.py +++ b/reflex/components/core/foreach.py @@ -2,6 +2,7 @@ from __future__ import annotations +import functools import inspect from typing import Any, Callable, Iterable @@ -10,6 +11,7 @@ from reflex.components.component import Component from reflex.components.tags import IterTag from reflex.constants import MemoizationMode from reflex.state import ComponentState +from reflex.utils.exceptions import UntypedVarError from reflex.vars.base import LiteralVar, Var @@ -50,6 +52,7 @@ class Foreach(Component): Raises: ForeachVarError: If the iterable is of type Any. TypeError: If the render function is a ComponentState. + UntypedVarError: If the iterable is of type Any without a type annotation. """ iterable = LiteralVar.create(iterable) if iterable._var_type == Any: @@ -71,8 +74,14 @@ class Foreach(Component): iterable=iterable, render_fn=render_fn, ) - # Keep a ref to a rendered component to determine correct imports/hooks/styles. - component.children = [component._render().render_component()] + try: + # Keep a ref to a rendered component to determine correct imports/hooks/styles. + component.children = [component._render().render_component()] + except UntypedVarError as e: + raise UntypedVarError( + f"Could not foreach over var `{iterable!s}` without a type annotation. " + "See https://reflex.dev/docs/library/dynamic-rendering/foreach/" + ) from e return component def _render(self) -> IterTag: @@ -97,9 +106,20 @@ class Foreach(Component): # Determine the index var name based on the params accepted by render_fn. props["index_var_name"] = params[1].name else: + render_fn = self.render_fn # Otherwise, use a deterministic index, based on the render function bytecode. code_hash = ( - hash(self.render_fn.__code__) + hash( + getattr( + render_fn, + "__code__", + ( + repr(self.render_fn) + if not isinstance(render_fn, functools.partial) + else render_fn.func.__code__ + ), + ) + ) .to_bytes( length=8, byteorder="big", diff --git a/reflex/components/core/html.py b/reflex/components/core/html.py index cfe46e591..2cad4f331 100644 --- a/reflex/components/core/html.py +++ b/reflex/components/core/html.py @@ -14,7 +14,7 @@ class Html(Div): """ # The HTML to render. - dangerouslySetInnerHTML: Var[Dict[str, str]] + dangerouslySetInnerHTML: Var[Dict[str, str]] # noqa: N815 @classmethod def create(cls, *children, **props): diff --git a/reflex/components/core/match.py b/reflex/components/core/match.py index 8b9382c89..5c31669a1 100644 --- a/reflex/components/core/match.py +++ b/reflex/components/core/match.py @@ -109,7 +109,7 @@ class Match(MemoizationLeaf): return cases, default @classmethod - def _create_case_var_with_var_data(cls, case_element): + def _create_case_var_with_var_data(cls, case_element: Any) -> Var: """Convert a case element into a Var.If the case is a Style type, we extract the var data and merge it with the newly created Var. @@ -222,7 +222,7 @@ class Match(MemoizationLeaf): 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 @@ class Match(MemoizationLeaf): _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 14205cc6b..897b89608 100644 --- a/reflex/components/core/upload.py +++ b/reflex/components/core/upload.py @@ -192,7 +192,7 @@ class GhostUpload(Fragment): class Upload(MemoizationLeaf): """A file upload component.""" - library = "react-dropzone@14.2.10" + library = "react-dropzone@14.3.5" tag = "" @@ -269,7 +269,7 @@ class Upload(MemoizationLeaf): 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 8a433c18c..4f1eb493e 100644 --- a/reflex/components/datadisplay/code.py +++ b/reflex/components/datadisplay/code.py @@ -14,7 +14,7 @@ from reflex.components.radix.themes.layout.box import Box from reflex.constants.colors import Color from reflex.event import set_clipboard from reflex.style import Style -from reflex.utils import console, format +from reflex.utils import format from reflex.utils.imports import ImportVar from reflex.vars.base import LiteralVar, Var, VarData @@ -382,7 +382,7 @@ for theme_name in dir(Theme): class CodeBlock(Component, MarkdownComponentMap): """A code block.""" - library = "react-syntax-highlighter@15.6.0" + library = "react-syntax-highlighter@15.6.1" tag = "PrismAsyncLight" @@ -438,6 +438,8 @@ class CodeBlock(Component, MarkdownComponentMap): can_copy = props.pop("can_copy", False) copy_button = props.pop("copy_button", None) + # react-syntax-highlighter doesn't have an explicit "light" or "dark" theme so we use one-light and one-dark + # themes respectively to ensure code compatibility. if "theme" not in props: # Default color scheme responds to global color mode. props["theme"] = color_mode_cond( @@ -445,20 +447,9 @@ class CodeBlock(Component, MarkdownComponentMap): dark=Theme.one_dark, ) - # react-syntax-highlighter doesn't have an explicit "light" or "dark" theme so we use one-light and one-dark - # themes respectively to ensure code compatibility. - if "theme" in props and not isinstance(props["theme"], Var): - props["theme"] = getattr(Theme, format.to_snake_case(props["theme"])) # type: ignore - console.deprecate( - feature_name="theme prop as string", - reason="Use code_block.themes instead.", - deprecation_version="0.6.0", - removal_version="0.7.0", - ) - 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 f71f97713..dfac0452a 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 @@ class DataEditor(NoSSRComponent): 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,9 +345,9 @@ class DataEditor(NoSSRComponent): 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])" "{"] + code = [f"function {data_callback}([col, row]){{"] columns_path = str(self.columns) data_path = str(self.data) @@ -385,7 +387,8 @@ class DataEditor(NoSSRComponent): raise ValueError( "DataEditor data must be an ArrayVar if rows is not provided." ) - props["rows"] = data.length() if isinstance(data, Var) else len(data) + + props["rows"] = data.length() if isinstance(data, ArrayVar) else len(data) if not isinstance(columns, Var) and len(columns): if types.is_dataframe(type(data)) or ( diff --git a/reflex/components/datadisplay/logo.py b/reflex/components/datadisplay/logo.py index d960b8cee..1c4c02001 100644 --- a/reflex/components/datadisplay/logo.py +++ b/reflex/components/datadisplay/logo.py @@ -15,10 +15,8 @@ def svg_logo(color: Union[str, rx.Var[str]] = rx.color_mode_cond("#110F1F", "whi The Reflex logo SVG. """ - def logo_path(d): - return rx.el.svg.path( - d=d, - ) + def logo_path(d: str): + return rx.el.svg.path(d=d) paths = [ "M0 11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 11.5999V7.1199H8.96V11.5999H6.72Z", diff --git a/reflex/components/datadisplay/shiki_code_block.py b/reflex/components/datadisplay/shiki_code_block.py index 3b6bce8a1..a4aaec1d4 100644 --- a/reflex/components/datadisplay/shiki_code_block.py +++ b/reflex/components/datadisplay/shiki_code_block.py @@ -602,7 +602,7 @@ class ShikiCodeBlock(Component, MarkdownComponentMap): 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", {})) @@ -621,18 +621,22 @@ class ShikiCodeBlock(Component, MarkdownComponentMap): Returns: Imports for the component. + + Raises: + ValueError: If the transformers are not of type LiteralVar. """ imports = defaultdict(list) + if not isinstance(self.transformers, LiteralVar): + raise ValueError( + f"transformers should be a LiteralVar type. Got {type(self.transformers)} instead." + ) for transformer in self.transformers._var_value: if isinstance(transformer, ShikiBaseTransformers): imports[transformer.library].extend( [ImportVar(tag=str(fn)) for fn in transformer.fns] ) - ( + if transformer.library not in self.lib_dependencies: self.lib_dependencies.append(transformer.library) - if transformer.library not in self.lib_dependencies - else None - ) return imports @classmethod @@ -653,8 +657,9 @@ class ShikiCodeBlock(Component, MarkdownComponentMap): 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 +762,13 @@ class ShikiHighLevelCodeBlock(ShikiCodeBlock): 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/dynamic.py b/reflex/components/dynamic.py index 806d610df..d4efcd293 100644 --- a/reflex/components/dynamic.py +++ b/reflex/components/dynamic.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Union from reflex import constants from reflex.utils import imports -from reflex.utils.exceptions import DynamicComponentMissingLibrary +from reflex.utils.exceptions import DynamicComponentMissingLibraryError from reflex.utils.format import format_library_name from reflex.utils.serializers import serializer from reflex.vars import Var, get_unique_variable_name @@ -36,13 +36,15 @@ def bundle_library(component: Union["Component", str]): component: The component to bundle the library with. Raises: - DynamicComponentMissingLibrary: Raised when a dynamic component is missing a library. + DynamicComponentMissingLibraryError: Raised when a dynamic component is missing a library. """ if isinstance(component, str): bundled_libraries.add(component) return if component.library is None: - raise DynamicComponentMissingLibrary("Component must have a library to bundle.") + raise DynamicComponentMissingLibraryError( + "Component must have a library to bundle." + ) bundled_libraries.add(format_library_name(component.library)) diff --git a/reflex/components/el/constants/reflex.py b/reflex/components/el/constants/reflex.py index 05c298325..199edf569 100644 --- a/reflex/components/el/constants/reflex.py +++ b/reflex/components/el/constants/reflex.py @@ -48,4 +48,4 @@ PROP_TO_ELEMENTS = { 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/element.py b/reflex/components/el/element.py index 213cea65a..c9a58b1f6 100644 --- a/reflex/components/el/element.py +++ b/reflex/components/el/element.py @@ -6,7 +6,7 @@ from reflex.components.component import Component class Element(Component): """The base class for all raw HTML elements.""" - def __eq__(self, other): + def __eq__(self, other: object): """Two elements are equal if they have the same tag. Args: diff --git a/reflex/components/el/elements/forms.py b/reflex/components/el/elements/forms.py index 6b2d83c46..51ad201b2 100644 --- a/reflex/components/el/elements/forms.py +++ b/reflex/components/el/elements/forms.py @@ -102,7 +102,7 @@ class Fieldset(Element): name: Var[Union[str, int, bool]] -def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]: +def on_submit_event_spec() -> Tuple[Var[dict[str, Any]]]: """Event handler spec for the on_submit event. Returns: @@ -111,7 +111,7 @@ def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]: return (FORM_DATA,) -def on_submit_string_event_spec() -> Tuple[Var[Dict[str, str]]]: +def on_submit_string_event_spec() -> Tuple[Var[dict[str, str]]]: """Event handler spec for the on_submit event. Returns: @@ -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 @@ class Input(BaseHTML): (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/el/elements/forms.pyi b/reflex/components/el/elements/forms.pyi index dfab40b21..6dbff65b2 100644 --- a/reflex/components/el/elements/forms.pyi +++ b/reflex/components/el/elements/forms.pyi @@ -270,8 +270,8 @@ class Fieldset(Element): """ ... -def on_submit_event_spec() -> Tuple[Var[Dict[str, Any]]]: ... -def on_submit_string_event_spec() -> Tuple[Var[Dict[str, str]]]: ... +def on_submit_event_spec() -> Tuple[Var[dict[str, Any]]]: ... +def on_submit_string_event_spec() -> Tuple[Var[dict[str, str]]]: ... class Form(BaseHTML): @overload @@ -341,10 +341,10 @@ class Form(BaseHTML): on_submit: Optional[ Union[ Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, Any]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, Any]], BASE_STATE] ], Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, str]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, str]], BASE_STATE] ], ] ] = None, diff --git a/reflex/components/markdown/markdown.py b/reflex/components/markdown/markdown.py index 7c65c0d43..27bd5bd62 100644 --- a/reflex/components/markdown/markdown.py +++ b/reflex/components/markdown/markdown.py @@ -8,7 +8,7 @@ from functools import lru_cache from hashlib import md5 from typing import Any, Callable, Dict, Sequence, Union -from reflex.components.component import Component, CustomComponent +from reflex.components.component import BaseComponent, Component, CustomComponent from reflex.components.tags.tag import Tag from reflex.utils import types from reflex.utils.imports import ImportDict, ImportVar @@ -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 @@ class Markdown(Component): ), }, *[ - 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 @@ const {_LANGUAGE!s} = match ? match[1] : ''; 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) @@ -379,7 +379,9 @@ const {_LANGUAGE!s} = match ? match[1] : ''; # fallback to the default fn Var creation if the component is not a MarkdownComponentMap. return MarkdownComponentMap.create_map_fn_var(fn_body=formatted_component) - def _get_map_fn_custom_code_from_children(self, component) -> list[str]: + def _get_map_fn_custom_code_from_children( + self, component: BaseComponent + ) -> list[str]: """Recursively get markdown custom code from children components. Args: @@ -409,7 +411,7 @@ const {_LANGUAGE!s} = match ? match[1] : ''; return custom_code_list @staticmethod - def _component_map_hash(component_map) -> str: + def _component_map_hash(component_map: dict) -> str: inp = str( {tag: component(_MOCK_ARG) for tag, component in component_map.items()} ).encode() @@ -425,7 +427,7 @@ const {_LANGUAGE!s} = match ? match[1] : ''; 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 80940d228..a5fe79f07 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/image.py b/reflex/components/next/image.py index 2011505d8..20ba5a304 100644 --- a/reflex/components/next/image.py +++ b/reflex/components/next/image.py @@ -1,13 +1,17 @@ """Image component from next/image.""" +from __future__ import annotations + from typing import Any, Literal, Optional, Union from reflex.event import EventHandler, no_args_event_spec -from reflex.utils import types +from reflex.utils import console, types from reflex.vars.base import Var from .base import NextComponent +DEFAULT_W_H = "100%" + class Image(NextComponent): """Display an image.""" @@ -53,7 +57,7 @@ class Image(NextComponent): loading: Var[Literal["lazy", "eager"]] # A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur". - blurDataURL: Var[str] + blur_data_url: Var[str] # Fires when the image has loaded. on_load: EventHandler[no_args_event_spec] @@ -80,10 +84,18 @@ class Image(NextComponent): Returns: _type_: _description_ """ - style = props.get("style", {}) - DEFAULT_W_H = "100%" + if "blurDataURL" in props: + console.deprecate( + feature_name="blurDataURL", + reason="Use blur_data_url instead", + deprecation_version="0.7.0", + removal_version="0.8.0", + ) + props["blur_data_url"] = props.pop("blurDataURL") - def check_prop_type(prop_name, prop_value): + style = props.get("style", {}) + + def check_prop_type(prop_name: str, prop_value: int | str | None): if types.check_prop_in_allowed_types(prop_value, allowed_types=[int]): props[prop_name] = prop_value diff --git a/reflex/components/next/image.pyi b/reflex/components/next/image.pyi index dd9dd38c3..b8da4973d 100644 --- a/reflex/components/next/image.pyi +++ b/reflex/components/next/image.pyi @@ -11,6 +11,8 @@ from reflex.vars.base import Var from .base import NextComponent +DEFAULT_W_H = "100%" + class Image(NextComponent): @overload @classmethod @@ -30,7 +32,7 @@ class Image(NextComponent): loading: Optional[ Union[Literal["eager", "lazy"], Var[Literal["eager", "lazy"]]] ] = None, - blurDataURL: Optional[Union[Var[str], str]] = None, + blur_data_url: Optional[Union[Var[str], str]] = None, style: Optional[Style] = None, key: Optional[Any] = None, id: Optional[Any] = None, @@ -71,7 +73,7 @@ class Image(NextComponent): priority: When true, the image will be considered high priority and preload. Lazy loading is automatically disabled for images using priority. placeholder: A placeholder to use while the image is loading. Possible values are blur, empty, or data:image/.... Defaults to empty. loading: The loading behavior of the image. Defaults to lazy. Can hurt performance, recommended to use `priority` instead. - blurDataURL: A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur". + blur_data_url: A Data URL to be used as a placeholder image before the src image successfully loads. Only takes effect when combined with placeholder="blur". on_load: Fires when the image has loaded. on_error: Fires when the image has an error. style: The style of the component. diff --git a/reflex/components/next/link.py b/reflex/components/next/link.py index 0f7c81296..187618a09 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 3bdef7875..c85423d35 100644 --- a/reflex/components/plotly/plotly.py +++ b/reflex/components/plotly/plotly.py @@ -18,8 +18,8 @@ try: 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]]]: @@ -95,20 +95,20 @@ class Plotly(NoSSRComponent): library = "react-plotly.js@2.6.0" - lib_dependencies: List[str] = ["plotly.js@2.35.2"] + lib_dependencies: List[str] = ["plotly.js@2.35.3"] tag = "Plot" 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 adce134fc..779e714d9 100644 --- a/reflex/components/props.py +++ b/reflex/components/props.py @@ -48,7 +48,7 @@ class PropsBase(Base): class NoExtrasAllowedProps(Base): """A class that holds props to be passed or applied to a component with no extra props allowed.""" - def __init__(self, component_name=None, **kwargs): + def __init__(self, component_name: str | None = None, **kwargs): """Initialize the props. Args: @@ -62,13 +62,13 @@ class NoExtrasAllowedProps(Base): 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 f4e81666a..9a16627b5 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/accordion.py b/reflex/components/radix/primitives/accordion.py index 0ba618e21..90a1c41f0 100644 --- a/reflex/components/radix/primitives/accordion.py +++ b/reflex/components/radix/primitives/accordion.py @@ -10,6 +10,7 @@ from reflex.components.core.cond import cond from reflex.components.lucide.icon import Icon from reflex.components.radix.primitives.base import RadixPrimitiveComponent from reflex.components.radix.themes.base import LiteralAccentColor, LiteralRadius +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler from reflex.style import Style from reflex.vars import get_uuid_string_var @@ -196,8 +197,9 @@ class AccordionItem(AccordionComponent): # The header of the accordion item. header: Var[Union[Component, str]] + # The content of the accordion item. - content: Var[Union[Component, str]] = Var.create(None) + content: Var[Union[Component, str, None]] = Var.create(None) _valid_children: List[str] = [ "AccordionHeader", @@ -341,6 +343,8 @@ class AccordionTrigger(AccordionComponent): alias = "RadixAccordionTrigger" + _memoization_mode = MemoizationMode(recursive=False) + @classmethod def create(cls, *children, **props) -> Component: """Create the Accordion trigger component. @@ -485,11 +489,11 @@ to { Returns: The style of the component. """ - slideDown = LiteralVar.create( + slide_down = LiteralVar.create( "${slideDown} var(--animation-duration) var(--animation-easing)", ) - slideUp = LiteralVar.create( + slide_up = LiteralVar.create( "${slideUp} var(--animation-duration) var(--animation-easing)", ) @@ -503,8 +507,8 @@ to { "display": "block", "height": "var(--space-3)", }, - "&[data-state='open']": {"animation": slideDown}, - "&[data-state='closed']": {"animation": slideUp}, + "&[data-state='open']": {"animation": slide_down}, + "&[data-state='closed']": {"animation": slide_up}, _inherited_variant_selector("classic"): { "color": "var(--accent-contrast)", }, diff --git a/reflex/components/radix/primitives/accordion.pyi b/reflex/components/radix/primitives/accordion.pyi index 03208f496..447451d11 100644 --- a/reflex/components/radix/primitives/accordion.pyi +++ b/reflex/components/radix/primitives/accordion.pyi @@ -308,7 +308,9 @@ class AccordionItem(AccordionComponent): value: Optional[Union[Var[str], str]] = None, disabled: Optional[Union[Var[bool], bool]] = None, header: Optional[Union[Component, Var[Union[Component, str]], str]] = None, - content: Optional[Union[Component, Var[Union[Component, str]], str]] = None, + content: Optional[ + Union[Component, Var[Optional[Union[Component, str]]], str] + ] = None, color_scheme: Optional[ Union[ Literal[ diff --git a/reflex/components/radix/primitives/drawer.py b/reflex/components/radix/primitives/drawer.py index ed57dcbd8..30d1a6ae3 100644 --- a/reflex/components/radix/primitives/drawer.py +++ b/reflex/components/radix/primitives/drawer.py @@ -10,6 +10,7 @@ from reflex.components.component import Component, ComponentNamespace from reflex.components.radix.primitives.base import RadixPrimitiveComponent from reflex.components.radix.themes.base import Theme from reflex.components.radix.themes.layout.flex import Flex +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -66,7 +67,7 @@ class DrawerRoot(DrawerComponent): scroll_lock_timeout: Var[int] # When `True`, it prevents scroll restoration. Defaults to `True`. - preventScrollRestoration: Var[bool] + prevent_scroll_restoration: Var[bool] # Enable background scaling, it requires container element with `vaul-drawer-wrapper` attribute to scale its background. should_scale_background: Var[bool] @@ -83,7 +84,9 @@ 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) + + _memoization_mode = MemoizationMode(recursive=False) @classmethod def create(cls, *children: Any, **props: Any) -> Component: diff --git a/reflex/components/radix/primitives/drawer.pyi b/reflex/components/radix/primitives/drawer.pyi index 1ca1e4325..bb2890fea 100644 --- a/reflex/components/radix/primitives/drawer.pyi +++ b/reflex/components/radix/primitives/drawer.pyi @@ -81,7 +81,7 @@ class DrawerRoot(DrawerComponent): snap_points: Optional[List[Union[float, str]]] = None, fade_from_index: Optional[Union[Var[int], int]] = None, scroll_lock_timeout: Optional[Union[Var[int], int]] = None, - preventScrollRestoration: Optional[Union[Var[bool], bool]] = None, + prevent_scroll_restoration: Optional[Union[Var[bool], bool]] = None, should_scale_background: Optional[Union[Var[bool], bool]] = None, close_threshold: Optional[Union[Var[float], float]] = None, as_child: Optional[Union[Var[bool], bool]] = None, @@ -129,7 +129,7 @@ class DrawerRoot(DrawerComponent): snap_points: Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Also Accept px values, which doesn't take screen height into account. fade_from_index: Index of a snapPoint from which the overlay fade should be applied. Defaults to the last snap point. scroll_lock_timeout: Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms - preventScrollRestoration: When `True`, it prevents scroll restoration. Defaults to `True`. + prevent_scroll_restoration: When `True`, it prevents scroll restoration. Defaults to `True`. should_scale_background: Enable background scaling, it requires container element with `vaul-drawer-wrapper` attribute to scale its background. close_threshold: Number between 0 and 1 that determines when the drawer should be closed. as_child: Change the default rendered element for the one passed as a child. @@ -567,7 +567,7 @@ class Drawer(ComponentNamespace): snap_points: Optional[List[Union[float, str]]] = None, fade_from_index: Optional[Union[Var[int], int]] = None, scroll_lock_timeout: Optional[Union[Var[int], int]] = None, - preventScrollRestoration: Optional[Union[Var[bool], bool]] = None, + prevent_scroll_restoration: Optional[Union[Var[bool], bool]] = None, should_scale_background: Optional[Union[Var[bool], bool]] = None, close_threshold: Optional[Union[Var[float], float]] = None, as_child: Optional[Union[Var[bool], bool]] = None, @@ -615,7 +615,7 @@ class Drawer(ComponentNamespace): snap_points: Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Also Accept px values, which doesn't take screen height into account. fade_from_index: Index of a snapPoint from which the overlay fade should be applied. Defaults to the last snap point. scroll_lock_timeout: Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms - preventScrollRestoration: When `True`, it prevents scroll restoration. Defaults to `True`. + prevent_scroll_restoration: When `True`, it prevents scroll restoration. Defaults to `True`. should_scale_background: Enable background scaling, it requires container element with `vaul-drawer-wrapper` attribute to scale its background. close_threshold: Number between 0 and 1 that determines when the drawer should be closed. as_child: Change the default rendered element for the one passed as a child. diff --git a/reflex/components/radix/primitives/form.pyi b/reflex/components/radix/primitives/form.pyi index 83e65a54d..d06b57090 100644 --- a/reflex/components/radix/primitives/form.pyi +++ b/reflex/components/radix/primitives/form.pyi @@ -132,10 +132,10 @@ class FormRoot(FormComponent, HTMLForm): on_submit: Optional[ Union[ Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, Any]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, Any]], BASE_STATE] ], Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, str]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, str]], BASE_STATE] ], ] ] = None, @@ -608,10 +608,10 @@ class Form(FormRoot): on_submit: Optional[ Union[ Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, Any]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, Any]], BASE_STATE] ], Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, str]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, str]], BASE_STATE] ], ] ] = None, @@ -741,10 +741,10 @@ class FormNamespace(ComponentNamespace): on_submit: Optional[ Union[ Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, Any]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, Any]], BASE_STATE] ], Union[ - EventType[[], BASE_STATE], EventType[[Dict[str, str]], BASE_STATE] + EventType[[], BASE_STATE], EventType[[dict[str, str]], BASE_STATE] ], ] ] = None, diff --git a/reflex/components/radix/primitives/progress.py b/reflex/components/radix/primitives/progress.py index 72aee1038..5fcc52f1b 100644 --- a/reflex/components/radix/primitives/progress.py +++ b/reflex/components/radix/primitives/progress.py @@ -83,7 +83,7 @@ class ProgressIndicator(ProgressComponent): "&[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 68f39e32c..6136e3171 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 e93a26ef6..d9b7c0b02 100644 --- a/reflex/components/radix/themes/color_mode.py +++ b/reflex/components/radix/themes/color_mode.py @@ -17,7 +17,7 @@ rx.text( from __future__ import annotations -from typing import Dict, List, Literal, Optional, Union, get_args +from typing import Any, Dict, List, Literal, Optional, Union, get_args from reflex.components.component import BaseComponent from reflex.components.core.cond import Cond, color_mode_cond, cond @@ -78,17 +78,19 @@ position_map: Dict[str, List[str]] = { # needed to inverse contains for find -def _find(const: List[str], var): +def _find(const: List[str], var: Any): return LiteralArrayVar.create(const).contains(var) -def _set_var_default(props, position, prop, default1, default2=""): +def _set_var_default( + props: dict, position: Any, prop: str, default1: str, default2: str = "" +): props.setdefault( prop, cond(_find(position_map[prop], position), default1, default2) ) -def _set_static_default(props, position, prop, default): +def _set_static_default(props: dict, position: Any, prop: str, default: str): if prop in position: props.setdefault(prop, default) @@ -115,12 +117,12 @@ class ColorModeIconButton(IconButton): 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") @@ -142,7 +144,7 @@ class ColorModeIconButton(IconButton): if allow_system: - def color_mode_item(_color_mode): + def color_mode_item(_color_mode: str): return dropdown_menu.item( _color_mode.title(), on_click=set_color_mode(_color_mode) ) diff --git a/reflex/components/radix/themes/components/alert_dialog.py b/reflex/components/radix/themes/components/alert_dialog.py index 36d38532c..bc5e2dc7e 100644 --- a/reflex/components/radix/themes/components/alert_dialog.py +++ b/reflex/components/radix/themes/components/alert_dialog.py @@ -5,6 +5,7 @@ from typing import Literal from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive from reflex.components.el import elements +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -33,6 +34,8 @@ class AlertDialogTrigger(RadixThemesTriggerComponent): tag = "AlertDialog.Trigger" + _memoization_mode = MemoizationMode(recursive=False) + class AlertDialogContent(elements.Div, RadixThemesComponent): """Contains the content of the dialog. This component is based on the div element.""" diff --git a/reflex/components/radix/themes/components/card.py b/reflex/components/radix/themes/components/card.py index 30823de56..e99ea9cef 100644 --- a/reflex/components/radix/themes/components/card.py +++ b/reflex/components/radix/themes/components/card.py @@ -20,7 +20,7 @@ class Card(elements.Div, RadixThemesComponent): # Card size: "1" - "5" size: Var[Responsive[Literal["1", "2", "3", "4", "5"],]] - # Variant of Card: "solid" | "soft" | "outline" | "ghost" + # Variant of Card: "surface" | "classic" | "ghost" variant: Var[Literal["surface", "classic", "ghost"]] diff --git a/reflex/components/radix/themes/components/card.pyi b/reflex/components/radix/themes/components/card.pyi index d8ab6c06b..e515982e4 100644 --- a/reflex/components/radix/themes/components/card.pyi +++ b/reflex/components/radix/themes/components/card.pyi @@ -94,7 +94,7 @@ class Card(elements.Div, RadixThemesComponent): *children: Child components. as_child: Change the default rendered element for the one passed as a child, merging their props and behavior. size: Card size: "1" - "5" - variant: Variant of Card: "solid" | "soft" | "outline" | "ghost" + variant: Variant of Card: "surface" | "classic" | "ghost" access_key: Provides a hint for generating a keyboard shortcut for the current element. auto_capitalize: Controls whether and how text input is automatically capitalized as it is entered/edited by the user. content_editable: Indicates whether the element's content is editable. diff --git a/reflex/components/radix/themes/components/context_menu.py b/reflex/components/radix/themes/components/context_menu.py index f8512a902..60d23db1a 100644 --- a/reflex/components/radix/themes/components/context_menu.py +++ b/reflex/components/radix/themes/components/context_menu.py @@ -4,6 +4,7 @@ from typing import Dict, List, Literal, Union from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -55,6 +56,8 @@ class ContextMenuTrigger(RadixThemesComponent): _invalid_children: List[str] = ["ContextMenuContent"] + _memoization_mode = MemoizationMode(recursive=False) + class ContextMenuContent(RadixThemesComponent): """The component that pops out when the context menu is open.""" @@ -153,6 +156,8 @@ class ContextMenuSubTrigger(RadixThemesComponent): _valid_parents: List[str] = ["ContextMenuContent", "ContextMenuSub"] + _memoization_mode = MemoizationMode(recursive=False) + class ContextMenuSubContent(RadixThemesComponent): """The component that pops out when a submenu is open.""" diff --git a/reflex/components/radix/themes/components/dialog.py b/reflex/components/radix/themes/components/dialog.py index 1b7c3b532..ce6e52cb5 100644 --- a/reflex/components/radix/themes/components/dialog.py +++ b/reflex/components/radix/themes/components/dialog.py @@ -5,6 +5,7 @@ from typing import Literal from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive from reflex.components.el import elements +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -31,6 +32,8 @@ class DialogTrigger(RadixThemesTriggerComponent): tag = "Dialog.Trigger" + _memoization_mode = MemoizationMode(recursive=False) + class DialogTitle(RadixThemesComponent): """Title component to display inside a Dialog modal.""" diff --git a/reflex/components/radix/themes/components/dropdown_menu.py b/reflex/components/radix/themes/components/dropdown_menu.py index abce3e3bb..6d5709e11 100644 --- a/reflex/components/radix/themes/components/dropdown_menu.py +++ b/reflex/components/radix/themes/components/dropdown_menu.py @@ -4,6 +4,7 @@ from typing import Dict, List, Literal, Union from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -60,6 +61,8 @@ class DropdownMenuTrigger(RadixThemesTriggerComponent): _invalid_children: List[str] = ["DropdownMenuContent"] + _memoization_mode = MemoizationMode(recursive=False) + class DropdownMenuContent(RadixThemesComponent): """The Dropdown Menu Content component that pops out when the dropdown menu is open.""" @@ -143,6 +146,8 @@ class DropdownMenuSubTrigger(RadixThemesTriggerComponent): _valid_parents: List[str] = ["DropdownMenuContent", "DropdownMenuSub"] + _memoization_mode = MemoizationMode(recursive=False) + class DropdownMenuSub(RadixThemesComponent): """Contains all the parts of a submenu.""" diff --git a/reflex/components/radix/themes/components/hover_card.py b/reflex/components/radix/themes/components/hover_card.py index bd5489ce6..9e7aa4688 100644 --- a/reflex/components/radix/themes/components/hover_card.py +++ b/reflex/components/radix/themes/components/hover_card.py @@ -5,6 +5,7 @@ from typing import Dict, Literal, Union from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive from reflex.components.el import elements +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, passthrough_event_spec from reflex.vars.base import Var @@ -37,6 +38,8 @@ class HoverCardTrigger(RadixThemesTriggerComponent): tag = "HoverCard.Trigger" + _memoization_mode = MemoizationMode(recursive=False) + class HoverCardContent(elements.Div, RadixThemesComponent): """Contains the content of the open hover card.""" diff --git a/reflex/components/radix/themes/components/icon_button.py b/reflex/components/radix/themes/components/icon_button.py index 68c67485a..aafb9e1eb 100644 --- a/reflex/components/radix/themes/components/icon_button.py +++ b/reflex/components/radix/themes/components/icon_button.py @@ -22,6 +22,8 @@ from ..base import ( LiteralButtonSize = Literal["1", "2", "3", "4"] +RADIX_TO_LUCIDE_SIZE = {"1": 12, "2": 24, "3": 36, "4": 48} + class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent): """A button designed specifically for usage with a single icon.""" @@ -72,8 +74,6 @@ class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent): "IconButton requires a child icon. Pass a string as the first child or a rx.icon." ) if "size" in props: - RADIX_TO_LUCIDE_SIZE = {"1": 12, "2": 24, "3": 36, "4": 48} - if isinstance(props["size"], str): children[0].size = RADIX_TO_LUCIDE_SIZE[props["size"]] else: diff --git a/reflex/components/radix/themes/components/icon_button.pyi b/reflex/components/radix/themes/components/icon_button.pyi index abf77e07b..bdb0fe845 100644 --- a/reflex/components/radix/themes/components/icon_button.pyi +++ b/reflex/components/radix/themes/components/icon_button.pyi @@ -14,6 +14,7 @@ from reflex.vars.base import Var from ..base import RadixLoadingProp, RadixThemesComponent LiteralButtonSize = Literal["1", "2", "3", "4"] +RADIX_TO_LUCIDE_SIZE = {"1": 12, "2": 24, "3": 36, "4": 48} class IconButton(elements.Button, RadixLoadingProp, RadixThemesComponent): @overload diff --git a/reflex/components/radix/themes/components/popover.py b/reflex/components/radix/themes/components/popover.py index bdf5f4af3..4c0542cb7 100644 --- a/reflex/components/radix/themes/components/popover.py +++ b/reflex/components/radix/themes/components/popover.py @@ -5,6 +5,7 @@ from typing import Dict, Literal, Union from reflex.components.component import ComponentNamespace from reflex.components.core.breakpoints import Responsive from reflex.components.el import elements +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -34,6 +35,8 @@ class PopoverTrigger(RadixThemesTriggerComponent): tag = "Popover.Trigger" + _memoization_mode = MemoizationMode(recursive=False) + class PopoverContent(elements.Div, RadixThemesComponent): """Contains content to be rendered in the open popover.""" diff --git a/reflex/components/radix/themes/components/radio_cards.py b/reflex/components/radix/themes/components/radio_cards.py index e075a1ba2..4a9aefc99 100644 --- a/reflex/components/radix/themes/components/radio_cards.py +++ b/reflex/components/radix/themes/components/radio_cards.py @@ -85,6 +85,8 @@ class RadioCardsItem(RadixThemesComponent): # When true, indicates that the user must check the radio item before the owning form can be submitted. required: Var[bool] + _valid_parents: list[str] = ["RadioCardsRoot"] + class RadioCards(SimpleNamespace): """RadioCards components namespace.""" diff --git a/reflex/components/radix/themes/components/radio_group.py b/reflex/components/radix/themes/components/radio_group.py index 80b3ee10c..f34c92159 100644 --- a/reflex/components/radix/themes/components/radio_group.py +++ b/reflex/components/radix/themes/components/radio_group.py @@ -155,7 +155,7 @@ class HighLevelRadioGroup(RadixThemesComponent): 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/select.py b/reflex/components/radix/themes/components/select.py index 45e5712bc..6ac992380 100644 --- a/reflex/components/radix/themes/components/select.py +++ b/reflex/components/radix/themes/components/select.py @@ -5,6 +5,7 @@ from typing import List, Literal, Union import reflex as rx from reflex.components.component import Component, ComponentNamespace from reflex.components.core.breakpoints import Responsive +from reflex.constants.compiler import MemoizationMode from reflex.event import no_args_event_spec, passthrough_event_spec from reflex.vars.base import Var @@ -69,6 +70,8 @@ class SelectTrigger(RadixThemesComponent): _valid_parents: List[str] = ["SelectRoot"] + _memoization_mode = MemoizationMode(recursive=False) + class SelectContent(RadixThemesComponent): """The component that pops out when the select is open.""" diff --git a/reflex/components/radix/themes/components/tabs.py b/reflex/components/radix/themes/components/tabs.py index adfb32fab..7b5e5f475 100644 --- a/reflex/components/radix/themes/components/tabs.py +++ b/reflex/components/radix/themes/components/tabs.py @@ -7,6 +7,7 @@ from typing import Any, Dict, List, Literal from reflex.components.component import Component, ComponentNamespace from reflex.components.core.breakpoints import Responsive from reflex.components.core.colors import color +from reflex.constants.compiler import MemoizationMode from reflex.event import EventHandler, passthrough_event_spec from reflex.vars.base import Var @@ -95,6 +96,8 @@ class TabsTrigger(RadixThemesComponent): _valid_parents: List[str] = ["TabsList"] + _memoization_mode = MemoizationMode(recursive=False) + @classmethod def create(cls, *children, **props) -> Component: """Create a TabsTrigger component. diff --git a/reflex/components/radix/themes/components/text_area.py b/reflex/components/radix/themes/components/text_area.py index 83fa8a593..caf98eb2d 100644 --- a/reflex/components/radix/themes/components/text_area.py +++ b/reflex/components/radix/themes/components/text_area.py @@ -96,5 +96,17 @@ class TextArea(RadixThemesComponent, elements.Textarea): return DebounceInput.create(super().create(*children, **props)) return super().create(*children, **props) + def add_style(self): + """Add the style to the component. + + Returns: + The style of the component. + """ + added_style: dict[str, dict] = {} + added_style.setdefault("& textarea", {}) + if "padding" in self.style: + added_style["& textarea"]["padding"] = self.style.pop("padding") + return added_style + text_area = TextArea.create diff --git a/reflex/components/radix/themes/components/text_area.pyi b/reflex/components/radix/themes/components/text_area.pyi index f0903ba98..e1e40c936 100644 --- a/reflex/components/radix/themes/components/text_area.pyi +++ b/reflex/components/radix/themes/components/text_area.pyi @@ -268,4 +268,6 @@ class TextArea(RadixThemesComponent, elements.Textarea): """ ... + def add_style(self): ... + text_area = TextArea.create diff --git a/reflex/components/radix/themes/components/text_field.py b/reflex/components/radix/themes/components/text_field.py index c8bdab443..130fb7aed 100644 --- a/reflex/components/radix/themes/components/text_field.py +++ b/reflex/components/radix/themes/components/text_field.py @@ -105,7 +105,7 @@ class TextFieldRoot(elements.Input, RadixThemesComponent): (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/components/tooltip.py b/reflex/components/radix/themes/components/tooltip.py index 07bab1a4a..53ec35264 100644 --- a/reflex/components/radix/themes/components/tooltip.py +++ b/reflex/components/radix/themes/components/tooltip.py @@ -28,6 +28,9 @@ LiteralStickyType = Literal[ ] +ARIA_LABEL_KEY = "aria_label" + + # The Tooltip inherits props from the Tooltip.Root, Tooltip.Portal, Tooltip.Content class Tooltip(RadixThemesComponent): """Floating element that provides a control with contextual information via pointer or focus.""" @@ -104,7 +107,6 @@ class Tooltip(RadixThemesComponent): Returns: The created component. """ - ARIA_LABEL_KEY = "aria_label" if props.get(ARIA_LABEL_KEY) is not None: props[format.to_kebab_case(ARIA_LABEL_KEY)] = props.pop(ARIA_LABEL_KEY) diff --git a/reflex/components/radix/themes/components/tooltip.pyi b/reflex/components/radix/themes/components/tooltip.pyi index fab1d0c12..0786bfada 100644 --- a/reflex/components/radix/themes/components/tooltip.pyi +++ b/reflex/components/radix/themes/components/tooltip.pyi @@ -14,6 +14,7 @@ from ..base import RadixThemesComponent LiteralSideType = Literal["top", "right", "bottom", "left"] LiteralAlignType = Literal["start", "center", "end"] LiteralStickyType = Literal["partial", "always"] +ARIA_LABEL_KEY = "aria_label" class Tooltip(RadixThemesComponent): @overload diff --git a/reflex/components/radix/themes/layout/__init__.pyi b/reflex/components/radix/themes/layout/__init__.pyi index 6712a3068..21fc8d921 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 a306e19a4..04fcb6ae5 100644 --- a/reflex/components/radix/themes/layout/list.py +++ b/reflex/components/radix/themes/layout/list.py @@ -72,7 +72,7 @@ class BaseList(Component, MarkdownComponentMap): 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 @@ -189,7 +189,7 @@ ordered_list = list_ns.ordered unordered_list = list_ns.unordered -def __getattr__(name): +def __getattr__(name: Any): # special case for when accessing list to avoid shadowing # python's built in list object. if name == "list": diff --git a/reflex/components/radix/themes/layout/stack.py b/reflex/components/radix/themes/layout/stack.py index d11c3488b..f017ff783 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 c93102408..09172b108 100644 --- a/reflex/components/radix/themes/typography/link.py +++ b/reflex/components/radix/themes/typography/link.py @@ -60,7 +60,7 @@ class Link(RadixThemesComponent, A, MemoizationLeaf, MarkdownComponentMap): 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 1663ddedf..cb6527915 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 fb0319ceb..7b7bb34e3 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/__init__.py b/reflex/components/recharts/__init__.py index 5e9e6fc14..6495c6583 100644 --- a/reflex/components/recharts/__init__.py +++ b/reflex/components/recharts/__init__.py @@ -70,6 +70,8 @@ _SUBMOD_ATTRS: dict = { "Label", "label_list", "LabelList", + "cell", + "Cell", ], "polar": [ "pie", diff --git a/reflex/components/recharts/__init__.pyi b/reflex/components/recharts/__init__.pyi index 8f6c4673f..61fc9b1e7 100644 --- a/reflex/components/recharts/__init__.pyi +++ b/reflex/components/recharts/__init__.pyi @@ -53,11 +53,13 @@ from .charts import radar_chart as radar_chart from .charts import radial_bar_chart as radial_bar_chart from .charts import scatter_chart as scatter_chart from .charts import treemap as treemap +from .general import Cell as Cell from .general import GraphingTooltip as GraphingTooltip from .general import Label as Label from .general import LabelList as LabelList from .general import Legend as Legend from .general import ResponsiveContainer as ResponsiveContainer +from .general import cell as cell from .general import graphing_tooltip as graphing_tooltip from .general import label as label from .general import label_list as label_list diff --git a/reflex/components/recharts/charts.py b/reflex/components/recharts/charts.py index bbe733244..3e9df4143 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] @@ -69,7 +69,7 @@ class ChartBase(RechartsCharts): ) @classmethod - def create(cls, *children, **props) -> Component: + def create(cls, *children: Any, **props: Any) -> Component: """Create a chart component. Args: @@ -84,19 +84,19 @@ class ChartBase(RechartsCharts): 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%", - } - # Provide min dimensions so the graph always appears, even if the outer container is zero-size. - if width is None: - dim_props["min_width"] = 200 - if height is None: - dim_props["min_height"] = 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. + 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, ) @@ -458,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/general.py b/reflex/components/recharts/general.py index 1769ea125..4b8c527d3 100644 --- a/reflex/components/recharts/general.py +++ b/reflex/components/recharts/general.py @@ -36,11 +36,11 @@ class ResponsiveContainer(Recharts, MemoizationLeaf): # The height of chart container. Can be a number or string. Default: "100%" height: Var[Union[int, str]] - # The minimum width of chart container. Number - min_width: Var[int] + # The minimum width of chart container. Number or string. + min_width: Var[Union[int, str]] - # The minimum height of chart container. Number - min_height: Var[int] + # The minimum height of chart container. Number or string. + min_height: Var[Union[int, str]] # If specified a positive number, debounced function will be used to handle the resize event. Default: 0 debounce: Var[int] @@ -242,8 +242,23 @@ class LabelList(Recharts): stroke: Var[Union[str, Color]] = LiteralVar.create("none") +class Cell(Recharts): + """A Cell component in Recharts.""" + + tag = "Cell" + + alias = "RechartsCell" + + # The presentation attribute of a rectangle in bar or a sector in pie. + fill: Var[str | Color] + + # The presentation attribute of a rectangle in bar or a sector in pie. + stroke: Var[str | Color] + + responsive_container = ResponsiveContainer.create legend = Legend.create graphing_tooltip = GraphingTooltip.create label = Label.create label_list = LabelList.create +cell = Cell.create diff --git a/reflex/components/recharts/general.pyi b/reflex/components/recharts/general.pyi index 823a50fce..9c63d6de9 100644 --- a/reflex/components/recharts/general.pyi +++ b/reflex/components/recharts/general.pyi @@ -22,8 +22,8 @@ class ResponsiveContainer(Recharts, MemoizationLeaf): aspect: Optional[Union[Var[int], int]] = None, width: Optional[Union[Var[Union[int, str]], int, str]] = None, height: Optional[Union[Var[Union[int, str]], int, str]] = None, - min_width: Optional[Union[Var[int], int]] = None, - min_height: Optional[Union[Var[int], int]] = None, + min_width: Optional[Union[Var[Union[int, str]], int, str]] = None, + min_height: Optional[Union[Var[Union[int, str]], int, str]] = None, debounce: Optional[Union[Var[int], int]] = None, style: Optional[Style] = None, key: Optional[Any] = None, @@ -56,8 +56,8 @@ class ResponsiveContainer(Recharts, MemoizationLeaf): aspect: The aspect ratio of the container. The final aspect ratio of the SVG element will be (width / height) * aspect. Number width: The width of chart container. Can be a number or string. Default: "100%" height: The height of chart container. Can be a number or string. Default: "100%" - min_width: The minimum width of chart container. Number - min_height: The minimum height of chart container. Number + min_width: The minimum width of chart container. Number or string. + min_height: The minimum height of chart container. Number or string. debounce: If specified a positive number, debounced function will be used to handle the resize event. Default: 0 on_resize: If specified provides a callback providing the updated chart width and height values. style: The style of the component. @@ -482,8 +482,59 @@ class LabelList(Recharts): """ ... +class Cell(Recharts): + @overload + @classmethod + def create( # type: ignore + cls, + *children, + fill: Optional[Union[Color, Var[Union[Color, str]], str]] = None, + stroke: Optional[Union[Color, Var[Union[Color, str]], str]] = None, + style: Optional[Style] = None, + key: Optional[Any] = None, + id: Optional[Any] = None, + class_name: Optional[Any] = None, + autofocus: Optional[bool] = None, + custom_attrs: Optional[Dict[str, Union[Var, Any]]] = None, + on_blur: Optional[EventType[[], BASE_STATE]] = None, + on_click: Optional[EventType[[], BASE_STATE]] = None, + on_context_menu: Optional[EventType[[], BASE_STATE]] = None, + on_double_click: Optional[EventType[[], BASE_STATE]] = None, + on_focus: Optional[EventType[[], BASE_STATE]] = None, + on_mount: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_down: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_enter: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_leave: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_move: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_out: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_over: Optional[EventType[[], BASE_STATE]] = None, + on_mouse_up: Optional[EventType[[], BASE_STATE]] = None, + on_scroll: Optional[EventType[[], BASE_STATE]] = None, + on_unmount: Optional[EventType[[], BASE_STATE]] = None, + **props, + ) -> "Cell": + """Create the component. + + Args: + *children: The children of the component. + fill: The presentation attribute of a rectangle in bar or a sector in pie. + stroke: The presentation attribute of a rectangle in bar or a sector in pie. + style: The style of the component. + key: A unique key for the component. + id: The id for the component. + class_name: The class name for the component. + autofocus: Whether the component should take the focus once the page is loaded + custom_attrs: custom attribute + **props: The props of the component. + + Returns: + The component. + """ + ... + responsive_container = ResponsiveContainer.create legend = Legend.create graphing_tooltip = GraphingTooltip.create label = Label.create label_list = LabelList.create +cell = Cell.create diff --git a/reflex/components/recharts/polar.py b/reflex/components/recharts/polar.py index 1f4974d4c..77aa1ef5e 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] @@ -73,7 +73,7 @@ class Pie(Recharts): data: Var[List[Dict[str, Any]]] # Valid children components - _valid_children: List[str] = ["Cell", "LabelList"] + _valid_children: List[str] = ["Cell", "LabelList", "Bare"] # Stoke color. Default: rx.color("accent", 9) stroke: Var[Union[str, Color]] = LiteralVar.create(Color("accent", 9)) diff --git a/reflex/components/recharts/recharts.py b/reflex/components/recharts/recharts.py index b5a4ed113..0d1b692f1 100644 --- a/reflex/components/recharts/recharts.py +++ b/reflex/components/recharts/recharts.py @@ -1,6 +1,6 @@ """A component that wraps a recharts lib.""" -from typing import Dict, Literal +from typing import Literal from reflex.components.component import Component, MemoizationLeaf, NoSSRComponent @@ -8,16 +8,16 @@ from reflex.components.component import Component, MemoizationLeaf, NoSSRCompone class Recharts(Component): """A component that wraps a recharts lib.""" - library = "recharts@2.13.0" + library = "recharts@2.15.0" - def _get_style(self) -> Dict: + def _get_style(self) -> dict: return {"wrapperStyle": self.style} class RechartsCharts(NoSSRComponent, MemoizationLeaf): """A component that wraps a recharts lib.""" - library = "recharts@2.13.0" + library = "recharts@2.15.0" LiteralAnimationEasing = Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"] diff --git a/reflex/components/sonner/toast.py b/reflex/components/sonner/toast.py index b978409ab..dbac8e733 100644 --- a/reflex/components/sonner/toast.py +++ b/reflex/components/sonner/toast.py @@ -132,7 +132,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps): # Function that gets called when the toast disappears automatically after it's timeout (duration` prop). on_auto_close: Optional[Any] - def dict(self, *args, **kwargs) -> dict[str, Any]: + def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: """Convert the object to a dictionary. Args: @@ -142,7 +142,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps): 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 @@ class ToastProps(PropsBase, NoExtrasAllowedProps): class Toaster(Component): """A Toaster Component for displaying toast notifications.""" - library: str = "sonner@1.7.1" + library: str | None = "sonner@1.7.2" tag = "Toaster" @@ -222,6 +222,8 @@ class Toaster(Component): 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 @@ class Toaster(Component): 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) @@ -274,12 +276,12 @@ class Toaster(Component): return run_script(toast) @staticmethod - def toast_info(message: str | Var = "", **kwargs): + def toast_info(message: str | Var = "", **kwargs: Any): """Display an info toast message. Args: message: The message to display. - kwargs: Additional toast props. + **kwargs: Additional toast props. Returns: The toast event. @@ -287,12 +289,12 @@ class Toaster(Component): return Toaster.send_toast(message, level="info", **kwargs) @staticmethod - def toast_warning(message: str | Var = "", **kwargs): + def toast_warning(message: str | Var = "", **kwargs: Any): """Display a warning toast message. Args: message: The message to display. - kwargs: Additional toast props. + **kwargs: Additional toast props. Returns: The toast event. @@ -300,12 +302,12 @@ class Toaster(Component): return Toaster.send_toast(message, level="warning", **kwargs) @staticmethod - def toast_error(message: str | Var = "", **kwargs): + def toast_error(message: str | Var = "", **kwargs: Any): """Display an error toast message. Args: message: The message to display. - kwargs: Additional toast props. + **kwargs: Additional toast props. Returns: The toast event. @@ -313,12 +315,12 @@ class Toaster(Component): return Toaster.send_toast(message, level="error", **kwargs) @staticmethod - def toast_success(message: str | Var = "", **kwargs): + def toast_success(message: str | Var = "", **kwargs: Any): """Display a success toast message. Args: message: The message to display. - kwargs: Additional toast props. + **kwargs: Additional toast props. Returns: The toast event. @@ -350,7 +352,7 @@ class Toaster(Component): return run_script(dismiss_action) @classmethod - def create(cls, *children, **props) -> Component: + def create(cls, *children: Any, **props: Any) -> Component: """Create a toaster component. Args: diff --git a/reflex/components/sonner/toast.pyi b/reflex/components/sonner/toast.pyi index 7fd9fdf54..829e959d5 100644 --- a/reflex/components/sonner/toast.pyi +++ b/reflex/components/sonner/toast.pyi @@ -51,7 +51,7 @@ class ToastProps(PropsBase, NoExtrasAllowedProps): on_dismiss: Optional[Any] on_auto_close: Optional[Any] - def dict(self, *args, **kwargs) -> dict[str, Any]: ... + def dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... class Toaster(Component): is_used: ClassVar[bool] = False @@ -62,13 +62,13 @@ class Toaster(Component): message: str | Var = "", level: str | None = None, **props ) -> EventSpec: ... @staticmethod - def toast_info(message: str | Var = "", **kwargs): ... + def toast_info(message: str | Var = "", **kwargs: Any): ... @staticmethod - def toast_warning(message: str | Var = "", **kwargs): ... + def toast_warning(message: str | Var = "", **kwargs: Any): ... @staticmethod - def toast_error(message: str | Var = "", **kwargs): ... + def toast_error(message: str | Var = "", **kwargs: Any): ... @staticmethod - def toast_success(message: str | Var = "", **kwargs): ... + def toast_success(message: str | Var = "", **kwargs: Any): ... @staticmethod def toast_dismiss(id: Var | str | None = None): ... @overload diff --git a/reflex/components/suneditor/editor.py b/reflex/components/suneditor/editor.py index d40f0e9ad..3edf27545 100644 --- a/reflex/components/suneditor/editor.py +++ b/reflex/components/suneditor/editor.py @@ -3,7 +3,7 @@ from __future__ import annotations import enum -from typing import Dict, List, Literal, Optional, Tuple, Union +from typing import Any, Dict, List, Literal, Optional, Tuple, Union from reflex.base import Base from reflex.components.component import Component, NoSSRComponent @@ -115,7 +115,7 @@ class Editor(NoSSRComponent): # Alternatively to a string, a dict of your language can be passed to this prop. # Please refer to the library docs for this. # options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" | - # "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" + # "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" # default: "en". lang: Var[ Union[ @@ -244,11 +244,13 @@ class Editor(NoSSRComponent): } @classmethod - def create(cls, set_options: Optional[EditorOptions] = None, **props) -> Component: + def create( + cls, set_options: Optional[EditorOptions] = None, **props: Any + ) -> Component: """Create an instance of Editor. No children allowed. Args: - set_options(Optional[EditorOptions]): Configuration object to further configure the instance. + set_options: Configuration object to further configure the instance. **props: Any properties to be passed to the Editor Returns: diff --git a/reflex/components/suneditor/editor.pyi b/reflex/components/suneditor/editor.pyi index b52fd43da..5577220cb 100644 --- a/reflex/components/suneditor/editor.pyi +++ b/reflex/components/suneditor/editor.pyi @@ -171,8 +171,8 @@ class Editor(NoSSRComponent): """Create an instance of Editor. No children allowed. Args: - set_options(Optional[EditorOptions]): Configuration object to further configure the instance. - lang: Language of the editor. Alternatively to a string, a dict of your language can be passed to this prop. Please refer to the library docs for this. options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" | "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" default: "en". + set_options: Configuration object to further configure the instance. + lang: Language of the editor. Alternatively to a string, a dict of your language can be passed to this prop. Please refer to the library docs for this. options: "en" | "da" | "de" | "es" | "fr" | "ja" | "ko" | "pt_br" | "ru" | "zh_cn" | "ro" | "pl" | "ckb" | "lv" | "se" | "ua" | "he" | "it" default: "en". name: This is used to set the HTML form name of the editor. This means on HTML form submission, it will be submitted together with contents of the editor by the name provided. default_value: Sets the default value of the editor. This is useful if you don't want the on_change method to be called on render. If you want the on_change method to be called on render please use the set_contents prop width: Sets the width of the editor. px and percentage values are accepted, eg width="100%" or width="500px" default: 100% diff --git a/reflex/components/tags/iter_tag.py b/reflex/components/tags/iter_tag.py index 38ecaf81c..cb02ca000 100644 --- a/reflex/components/tags/iter_tag.py +++ b/reflex/components/tags/iter_tag.py @@ -41,14 +41,14 @@ class IterTag(Tag): 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/components/tags/tag.py b/reflex/components/tags/tag.py index 0587c61ed..983726e56 100644 --- a/reflex/components/tags/tag.py +++ b/reflex/components/tags/tag.py @@ -3,13 +3,33 @@ from __future__ import annotations import dataclasses -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Sequence, Union from reflex.event import EventChain from reflex.utils import format, types from reflex.vars.base import LiteralVar, Var +def render_prop(value: Any) -> Any: + """Render the prop. + + Args: + value: The value to render. + + Returns: + The rendered value. + """ + from reflex.components.component import BaseComponent + + if isinstance(value, BaseComponent): + return value.render() + if isinstance(value, Sequence) and not isinstance(value, str): + return [render_prop(v) for v in value] + if callable(value) and not isinstance(value, Var): + return None + return value + + @dataclasses.dataclass() class Tag: """A React tag.""" @@ -49,7 +69,7 @@ class Tag: """Set the tag's fields. Args: - kwargs: The fields to set. + **kwargs: The fields to set. Returns: The tag with the fields @@ -66,7 +86,9 @@ class Tag: Tuple[str, Any]: The field name and value. """ for field in dataclasses.fields(self): - yield field.name, getattr(self, field.name) + rendered_value = render_prop(getattr(self, field.name)) + if rendered_value is not None: + yield field.name, rendered_value def add_props(self, **kwargs: Optional[Any]) -> Tag: """Add props to the tag. diff --git a/reflex/config.py b/reflex/config.py index 7614417d5..6609067f9 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -12,6 +12,7 @@ import threading import urllib.parse from importlib.util import find_spec from pathlib import Path +from types import ModuleType from typing import ( TYPE_CHECKING, Any, @@ -389,7 +390,7 @@ class EnvVar(Generic[T]): os.environ[self.name] = str(value) -class env_var: # type: ignore +class env_var: # noqa: N801 # pyright: ignore [reportRedeclaration] """Descriptor for environment variables.""" name: str @@ -406,7 +407,7 @@ class env_var: # type: ignore self.default = default self.internal = internal - def __set_name__(self, owner, name): + def __set_name__(self, owner: Any, name: str): """Set the name of the descriptor. Args: @@ -415,7 +416,7 @@ class env_var: # type: ignore """ self.name = name - def __get__(self, instance, owner): + def __get__(self, instance: Any, owner: Any): """Get the EnvVar instance. Args: @@ -434,7 +435,7 @@ class env_var: # type: ignore if TYPE_CHECKING: - def env_var(default, internal=False) -> EnvVar: + def env_var(default: Any, internal: bool = False) -> EnvVar: """Typing helper for the env_var descriptor. Args: @@ -489,6 +490,9 @@ class EnvironmentVariables: # The working directory for the next.js commands. REFLEX_WEB_WORKDIR: EnvVar[Path] = env_var(Path(constants.Dirs.WEB)) + # The working directory for the states directory. + REFLEX_STATES_WORKDIR: EnvVar[Path] = env_var(Path(constants.Dirs.STATES)) + # Path to the alembic config file ALEMBIC_CONFIG: EnvVar[ExistingPath] = env_var(Path(constants.ALEMBIC_CONFIG)) @@ -555,9 +559,6 @@ class EnvironmentVariables: # Arguments to pass to the app harness driver. APP_HARNESS_DRIVER_ARGS: EnvVar[str] = env_var("") - # Where to save screenshots when tests fail. - SCREENSHOT_DIR: EnvVar[Optional[Path]] = env_var(None) - # Whether to check for outdated package versions. REFLEX_CHECK_LATEST_VERSION: EnvVar[bool] = env_var(True) @@ -599,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 @@ -607,6 +608,9 @@ class Config(Base): # The name of the app (should match the name of the app directory). app_name: str + # The path to the app module. + app_module_import: Optional[str] = None + # The log level to use. loglevel: constants.LogLevel = constants.LogLevel.DEFAULT @@ -699,6 +703,9 @@ class Config(Base): # Path to file containing key-values pairs to override in the environment; Dotenv format. env_file: Optional[str] = None + # Whether the app is running in the reflex cloud environment. + is_reflex_cloud: bool = False + def __init__(self, *args, **kwargs): """Initialize the config values. @@ -729,6 +736,19 @@ class Config(Base): "REDIS_URL is required when using the redis state manager." ) + @property + def app_module(self) -> ModuleType | None: + """Return the app module if `app_module_import` is set. + + Returns: + The app module. + """ + return ( + importlib.import_module(self.app_module_import) + if self.app_module_import + else None + ) + @property def module(self) -> str: """Get the module name of the app. @@ -736,6 +756,8 @@ class Config(Base): Returns: The module name. """ + if self.app_module is not None: + return self.app_module.__name__ return ".".join([self.app_name, self.app_name]) def update_from_env(self) -> dict[str, Any]: @@ -747,7 +769,7 @@ class Config(Base): """ 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) @@ -807,16 +829,16 @@ class Config(Base): if "api_url" not in self._non_default_attributes: # If running in Github Codespaces, override API_URL codespace_name = os.getenv("CODESPACE_NAME") - GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv( + github_codespaces_port_forwarding_domain = os.getenv( "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN" ) # If running on Replit.com interactively, override API_URL to ensure we maintain the backend_port replit_dev_domain = os.getenv("REPLIT_DEV_DOMAIN") backend_port = kwargs.get("backend_port", self.backend_port) - if codespace_name and GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN: + if codespace_name and github_codespaces_port_forwarding_domain: self.api_url = ( f"https://{codespace_name}-{kwargs.get('backend_port', self.backend_port)}" - f".{GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}" + f".{github_codespaces_port_forwarding_domain}" ) elif replit_dev_domain and backend_port: self.api_url = f"https://{replit_dev_domain}:{backend_port}" @@ -874,7 +896,7 @@ def get_config(reload: bool = False) -> Config: return cached_rxconfig.config with _config_lock: - sys_path = sys.path.copy() + orig_sys_path = sys.path.copy() sys.path.clear() sys.path.append(str(Path.cwd())) try: @@ -882,9 +904,14 @@ def get_config(reload: bool = False) -> Config: return _get_config() except Exception: # If the module import fails, try to import with the original sys.path. - sys.path.extend(sys_path) + sys.path.extend(orig_sys_path) return _get_config() finally: + # Find any entries added to sys.path by rxconfig.py itself. + extra_paths = [ + p for p in sys.path if p not in orig_sys_path and p != str(Path.cwd()) + ] # Restore the original sys.path. sys.path.clear() - sys.path.extend(sys_path) + sys.path.extend(extra_paths) + sys.path.extend(orig_sys_path) diff --git a/reflex/constants/__init__.py b/reflex/constants/__init__.py index e816da0f7..f5946bf5e 100644 --- a/reflex/constants/__init__.py +++ b/reflex/constants/__init__.py @@ -1,6 +1,7 @@ """The constants package.""" from .base import ( + APP_HARNESS_FLAG, COOKIES, IS_LINUX, IS_MACOS, diff --git a/reflex/constants/base.py b/reflex/constants/base.py index af96583ad..7fbcdf18a 100644 --- a/reflex/constants/base.py +++ b/reflex/constants/base.py @@ -52,7 +52,7 @@ class Dirs(SimpleNamespace): # The name of the postcss config file. POSTCSS_JS = "postcss.config.js" # The name of the states directory. - STATES = "states" + STATES = ".states" class Reflex(SimpleNamespace): @@ -75,6 +75,8 @@ class Reflex(SimpleNamespace): # If user sets REFLEX_DIR envroment variable use that instead. DIR = PlatformDirs(MODULE_NAME, False).user_data_path + LOGS_DIR = DIR / "logs" + # The root directory of the reflex library. ROOT_DIR = Path(__file__).parents[2] @@ -257,6 +259,7 @@ SESSION_STORAGE = "session_storage" # Testing variables. # Testing os env set by pytest when running a test case. PYTEST_CURRENT_TEST = "PYTEST_CURRENT_TEST" +APP_HARNESS_FLAG = "APP_HARNESS_FLAG" REFLEX_VAR_OPENING_TAG = "" REFLEX_VAR_CLOSING_TAG = "" diff --git a/reflex/constants/compiler.py b/reflex/constants/compiler.py index d98c04d76..9bc9978dc 100644 --- a/reflex/constants/compiler.py +++ b/reflex/constants/compiler.py @@ -1,10 +1,10 @@ """Compiler variables.""" +import dataclasses import enum from enum import Enum from types import SimpleNamespace -from reflex.base import Base from reflex.constants import Dirs from reflex.utils.imports import ImportVar @@ -28,6 +28,8 @@ class Ext(SimpleNamespace): ZIP = ".zip" # The extension for executable files on Windows. EXE = ".exe" + # The extension for markdown files. + MD = ".md" class CompileVars(SimpleNamespace): @@ -149,7 +151,8 @@ class MemoizationDisposition(enum.Enum): NEVER = "never" -class MemoizationMode(Base): +@dataclasses.dataclass(frozen=True) +class MemoizationMode: """The mode for memoizing a Component.""" # The conditions under which the component should be memoized. diff --git a/reflex/constants/config.py b/reflex/constants/config.py index 7425fd864..a49216c00 100644 --- a/reflex/constants/config.py +++ b/reflex/constants/config.py @@ -39,7 +39,14 @@ class GitIgnore(SimpleNamespace): # The gitignore file. FILE = Path(".gitignore") # Files to gitignore. - DEFAULTS = {Dirs.WEB, "*.db", "__pycache__/", "*.py[cod]", "assets/external/"} + DEFAULTS = { + Dirs.WEB, + Dirs.STATES, + "*.db", + "__pycache__/", + "*.py[cod]", + "assets/external/", + } class RequirementsTxt(SimpleNamespace): diff --git a/reflex/constants/installer.py b/reflex/constants/installer.py index f9dd26b5a..0a89240b3 100644 --- a/reflex/constants/installer.py +++ b/reflex/constants/installer.py @@ -37,10 +37,10 @@ class Bun(SimpleNamespace): """Bun constants.""" # The Bun version. - VERSION = "1.1.29" + VERSION = "1.2.0" # Min Bun Version - MIN_VERSION = "0.7.0" + MIN_VERSION = "1.1.0" # URL to bun install script. INSTALL_URL = "https://raw.githubusercontent.com/reflex-dev/reflex/main/scripts/bun_install.sh" @@ -178,21 +178,21 @@ class PackageJson(SimpleNamespace): PATH = "package.json" DEPENDENCIES = { - "@babel/standalone": "7.26.0", - "@emotion/react": "11.13.3", - "axios": "1.7.7", + "@babel/standalone": "7.26.6", + "@emotion/react": "11.14.0", + "axios": "1.7.9", "json5": "2.2.3", - "next": "15.1.4", + "next": "15.1.6", "next-sitemap": "4.2.3", - "next-themes": "0.4.3", + "next-themes": "0.4.4", "react": "18.3.1", "react-dom": "18.3.1", - "react-focus-lock": "2.13.2", + "react-focus-lock": "2.13.5", "socket.io-client": "4.8.1", "universal-cookie": "7.2.2", } DEV_DEPENDENCIES = { "autoprefixer": "10.4.20", - "postcss": "8.4.49", + "postcss": "8.5.1", "postcss-import": "16.1.0", } diff --git a/reflex/constants/style.py b/reflex/constants/style.py index a1d30bcca..5b31ce9b3 100644 --- a/reflex/constants/style.py +++ b/reflex/constants/style.py @@ -7,7 +7,7 @@ class Tailwind(SimpleNamespace): """Tailwind constants.""" # The Tailwindcss version - VERSION = "tailwindcss@3.4.15" + VERSION = "tailwindcss@3.4.17" # The Tailwind config. CONFIG = "tailwind.config.js" # Default Tailwind content paths diff --git a/reflex/custom_components/custom_components.py b/reflex/custom_components/custom_components.py index 4a169802f..a54004803 100644 --- a/reflex/custom_components/custom_components.py +++ b/reflex/custom_components/custom_components.py @@ -83,7 +83,7 @@ def _get_package_config(exit_on_fail: bool = True) -> dict: The package configuration. Raises: - Exit: If the pyproject.toml file is not found. + Exit: If the pyproject.toml file is not found and exit_on_fail is True. """ pyproject = Path(CustomComponents.PYPROJECT_TOML) try: @@ -421,12 +421,13 @@ def _run_commands_in_subprocess(cmds: list[str]) -> bool: console.debug(f"Running command: {' '.join(cmds)}") try: result = subprocess.run(cmds, capture_output=True, text=True, check=True) - console.debug(result.stdout) - return True except subprocess.CalledProcessError as cpe: console.error(cpe.stdout) console.error(cpe.stderr) return False + else: + console.debug(result.stdout) + return True def _make_pyi_files(): @@ -771,7 +772,7 @@ def _validate_project_info(): pyproject_toml = _get_package_config() project = pyproject_toml["project"] console.print( - f'Double check the information before publishing: {project["name"]} version {project["version"]}' + f"Double check the information before publishing: {project['name']} version {project['version']}" ) console.print("Update or enter to keep the current information.") @@ -783,7 +784,7 @@ def _validate_project_info(): author["name"] = console.ask("Author Name", default=author.get("name", "")) author["email"] = console.ask("Author Email", default=author.get("email", "")) - console.print(f'Current keywords are: {project.get("keywords") or []}') + console.print(f"Current keywords are: {project.get('keywords') or []}") keyword_action = console.ask( "Keep, replace or append?", choices=["k", "r", "a"], default="k" ) @@ -924,17 +925,18 @@ 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 file_extension = image_filepath.suffix try: image_file = image_filepath.read_bytes() - return image_file, file_extension except OSError as ose: console.error(f"Unable to read the {file_extension} file due to {ose}") raise typer.Exit(code=1) from ose + else: + return image_file, file_extension console.debug(f"File extension detected: {file_extension}") return None diff --git a/reflex/event.py b/reflex/event.py index 28852fde5..f35e88389 100644 --- a/reflex/event.py +++ b/reflex/event.py @@ -4,7 +4,6 @@ from __future__ import annotations import dataclasses import inspect -import sys import types import urllib.parse from base64 import b64encode @@ -25,7 +24,6 @@ from typing import ( overload, ) -import typing_extensions from typing_extensions import ( Concatenate, ParamSpec, @@ -38,9 +36,14 @@ from typing_extensions import ( ) from reflex import constants +from reflex.constants.compiler import CompileVars, Hooks, Imports from reflex.constants.state import FRONTEND_EVENT_STATE from reflex.utils import console, format -from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgTypeMismatch +from reflex.utils.exceptions import ( + EventFnArgMismatchError, + EventHandlerArgTypeMismatchError, + MissingAnnotationError, +) from reflex.utils.types import ArgsSpec, GenericType, typehint_issubclass from reflex.vars import VarData from reflex.vars.base import LiteralVar, Var @@ -96,32 +99,6 @@ _EVENT_FIELDS: set[str] = {f.name for f in dataclasses.fields(Event)} BACKGROUND_TASK_MARKER = "_reflex_background_task" -def background(fn, *, __internal_reflex_call: bool = False): - """Decorator to mark event handler as running in the background. - - Args: - fn: The function to decorate. - - Returns: - The same function, but with a marker set. - - - Raises: - TypeError: If the function is not a coroutine function or async generator. - """ - if not __internal_reflex_call: - console.deprecate( - "background-decorator", - "Use `rx.event(background=True)` instead.", - "0.6.5", - "0.7.0", - ) - if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn): - raise TypeError("Background task must be async function or generator.") - setattr(fn, BACKGROUND_TASK_MARKER, True) - return fn - - @dataclasses.dataclass( init=True, frozen=True, @@ -266,7 +243,7 @@ class EventHandler(EventActionsMixin): raise EventHandlerTypeError( f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}." ) from e - payload = tuple(zip(fn_args, values)) + payload = tuple(zip(fn_args, values, strict=False)) # Return the event spec. return EventSpec( @@ -286,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="") @@ -355,12 +332,12 @@ class EventSpec(EventActionsMixin): arg = None try: for arg in args: - values.append(LiteralVar.create(value=arg)) # noqa: PERF401 + values.append(LiteralVar.create(value=arg)) # noqa: PERF401, RUF100 except TypeError as e: raise EventHandlerTypeError( f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}." ) from e - new_payload = tuple(zip(fn_args, values)) + new_payload = tuple(zip(fn_args, values, strict=False)) return self.with_args(self.args + new_payload) @@ -557,13 +534,13 @@ class JavasciptKeyboardEvent: """Interface for a Javascript KeyboardEvent https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.""" key: str = "" - altKey: bool = False - ctrlKey: bool = False - metaKey: bool = False - shiftKey: bool = False + altKey: bool = False # noqa: N815 + ctrlKey: bool = False # noqa: N815 + metaKey: bool = False # noqa: N815 + shiftKey: bool = False # noqa: N815 -def input_event(e: Var[JavascriptInputEvent]) -> Tuple[Var[str]]: +def input_event(e: ObjectVar[JavascriptInputEvent]) -> Tuple[Var[str]]: """Get the value from an input event. Args: @@ -584,7 +561,9 @@ class KeyInputInfo(TypedDict): shift_key: bool -def key_event(e: Var[JavasciptKeyboardEvent]) -> Tuple[Var[str], Var[KeyInputInfo]]: +def key_event( + e: ObjectVar[JavasciptKeyboardEvent], +) -> Tuple[Var[str], Var[KeyInputInfo]]: """Get the key from a keyboard event. Args: @@ -594,7 +573,7 @@ def key_event(e: Var[JavasciptKeyboardEvent]) -> Tuple[Var[str], Var[KeyInputInf The key from the keyboard event. """ return ( - e.key, + e.key.to(str), Var.create( { "alt_key": e.altKey, @@ -602,7 +581,7 @@ def key_event(e: Var[JavasciptKeyboardEvent]) -> Tuple[Var[str], Var[KeyInputInf "meta_key": e.metaKey, "shift_key": e.shiftKey, }, - ), + ).to(KeyInputInfo), ) @@ -612,7 +591,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. @@ -640,9 +619,9 @@ class IdentityEventReturn(Generic[T], Protocol): @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 @@ -655,7 +634,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: @@ -669,9 +648,9 @@ def passthrough_event_spec(*event_types: Type[T]) -> IdentityEventReturn[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}", @@ -753,7 +732,7 @@ class FileUpload: # 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): @@ -800,7 +779,7 @@ def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec: 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( @@ -813,29 +792,10 @@ def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec: ) -@overload def redirect( path: str | Var[str], - is_external: Optional[bool] = None, + is_external: bool = False, replace: bool = False, -) -> EventSpec: ... - - -@overload -@typing_extensions.deprecated("`external` is deprecated use `is_external` instead") -def redirect( - path: str | Var[str], - is_external: Optional[bool] = None, - replace: bool = False, - external: Optional[bool] = None, -) -> EventSpec: ... - - -def redirect( - path: str | Var[str], - is_external: Optional[bool] = None, - replace: bool = False, - external: Optional[bool] = None, ) -> EventSpec: """Redirect to a new path. @@ -843,26 +803,10 @@ def redirect( path: The path to redirect to. is_external: Whether to open in new tab or not. replace: If True, the current page will not create a new history entry. - external(Deprecated): Whether to open in new tab or not. Returns: An event to redirect to the path. """ - if external is not None: - console.deprecate( - "The `external` prop in `rx.redirect`", - "use `is_external` instead.", - "0.6.6", - "0.7.0", - ) - - # is_external should take precedence over external. - is_external = ( - (False if external is None else external) - if is_external is None - else is_external - ) - return server_side( "_redirect", get_fn_signature(redirect), @@ -1108,13 +1052,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. @@ -1133,7 +1077,8 @@ def download( ) -def _callback_arg_spec(eval_result): +# This function seems unused. Check if we still need it. If not, remove in 0.7.0 +def _callback_arg_spec(eval_result: Any): """ArgSpec for call_script callback function. Args: @@ -1238,7 +1183,7 @@ def run_script( return call_function(ArgsFunctionOperation.create((), javascript_code), callback) -def get_event(state, event): +def get_event(state: BaseState, event: str): """Get the event from the given state. Args: @@ -1251,7 +1196,7 @@ def get_event(state, event): return f"{state.get_name()}.{event}" -def get_hydrate_event(state) -> str: +def get_hydrate_event(state: BaseState) -> str: """Get the name of the hydrate event for the state. Args: @@ -1279,13 +1224,16 @@ def call_event_handler( event_spec: The lambda that define the argument(s) to pass to the event handler. key: The key to pass to the event handler. + Raises: + EventHandlerArgTypeMismatchError: If the event handler arguments do not match the event spec. #noqa: DAR402 + TypeError: If the event handler arguments are invalid. + Returns: The event spec from calling the event handler. - # noqa: DAR401 failure - + #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( @@ -1320,10 +1268,15 @@ def call_event_handler( ), ) ) + type_match_found: dict[str, bool] = {} + delayed_exceptions: list[EventHandlerArgTypeMismatchError] = [] + + try: + type_hints_of_provided_callback = get_type_hints(event_callback.fn) + except NameError: + type_hints_of_provided_callback = {} if event_spec_return_types: - failures = [] - event_callback_spec = inspect.getfullargspec(event_callback.fn) for event_spec_index, event_spec_return_type in enumerate( @@ -1335,43 +1288,35 @@ def call_event_handler( arg if get_origin(arg) is not Var else get_args(arg)[0] for arg in args ] - try: - type_hints_of_provided_callback = get_type_hints(event_callback.fn) - except NameError: - type_hints_of_provided_callback = {} - - failed_type_check = False - # check that args of event handler are matching the spec if type hints are provided for i, arg in enumerate(event_callback_spec.args[1:]): if arg not in type_hints_of_provided_callback: continue + type_match_found.setdefault(arg, False) + try: compare_result = typehint_issubclass( args_types_without_vars[i], type_hints_of_provided_callback[arg] ) - except TypeError: - # TODO: In 0.7.0, remove this block and raise the exception - # raise TypeError( - # f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_handler.fn.__qualname__} provided for {key}." # noqa: ERA001 - # ) from e - console.warn( + except TypeError as te: + raise TypeError( f"Could not compare types {args_types_without_vars[i]} and {type_hints_of_provided_callback[arg]} for argument {arg} of {event_callback.fn.__qualname__} provided for {key}." - ) - compare_result = False + ) from te if compare_result: + type_match_found[arg] = True continue else: - failure = EventHandlerArgTypeMismatch( - f"Event handler {key} expects {args_types_without_vars[i]} for argument {arg} but got {type_hints_of_provided_callback[arg]} as annotated in {event_callback.fn.__qualname__} instead." + type_match_found[arg] = False + delayed_exceptions.append( + EventHandlerArgTypeMismatchError( + f"Event handler {key} expects {args_types_without_vars[i]} for argument {arg} but got {type_hints_of_provided_callback[arg]} as annotated in {event_callback.fn.__qualname__} instead." + ) ) - failures.append(failure) - failed_type_check = True - break - if not failed_type_check: + if all(type_match_found.values()): + delayed_exceptions.clear() if event_spec_index: args = get_args(event_spec_return_types[0]) @@ -1393,17 +1338,12 @@ def call_event_handler( f"Event handler {key} expects ({expect_string}) -> () but got ({given_string}) -> () as annotated in {event_callback.fn.__qualname__} instead. " f"This may lead to unexpected behavior but is intentionally ignored for {key}." ) - return event_callback(*event_spec_args) + break - if failures: - console.deprecate( - "Mismatched event handler argument types", - "\n".join([str(f) for f in failures]), - "0.6.5", - "0.7.0", - ) + 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): @@ -1415,31 +1355,31 @@ def unwrap_var_annotation(annotation: GenericType): Returns: The unwrapped annotation. """ - if get_origin(annotation) is Var and (args := get_args(annotation)): + if get_origin(annotation) in (Var, ObjectVar) and (args := get_args(annotation)): return args[0] return annotation -def resolve_annotation(annotations: dict[str, Any], arg_name: str): +def resolve_annotation(annotations: dict[str, Any], arg_name: str, spec: ArgsSpec): """Resolve the annotation for the given argument name. Args: annotations: The annotations. arg_name: The argument name. + spec: The specs which the annotations come from. + + Raises: + MissingAnnotationError: If the annotation is missing for non-lambda methods. Returns: The resolved annotation. """ annotation = annotations.get(arg_name) if annotation is None: - console.deprecate( - feature_name="Unannotated event handler arguments", - reason="Provide type annotations for event handler arguments.", - deprecation_version="0.6.3", - removal_version="0.7.0", - ) - # Allow arbitrary attribute access two levels deep until removed. - return Dict[str, dict] + if not isinstance(spec, types.LambdaType): + raise MissingAnnotationError(var_name=arg_name) + else: + return dict[str, dict] return annotation @@ -1461,7 +1401,13 @@ def parse_args_spec(arg_spec: ArgsSpec | Sequence[ArgsSpec]): arg_spec( *[ Var(f"_{l_arg}").to( - unwrap_var_annotation(resolve_annotation(annotations, l_arg)) + unwrap_var_annotation( + resolve_annotation( + annotations, + l_arg, + spec=arg_spec, + ) + ) ) for l_arg in spec.args ] @@ -1477,7 +1423,7 @@ def check_fn_match_arg_spec( func_name: str | None = None, ): """Ensures that the function signature matches the passed argument specification - or raises an EventFnArgMismatch if they do not. + or raises an EventFnArgMismatchError if they do not. Args: user_func: The function to be validated. @@ -1487,7 +1433,7 @@ def check_fn_match_arg_spec( func_name: The name of the function to be validated. Raises: - EventFnArgMismatch: Raised if the number of mandatory arguments do not match + EventFnArgMismatchError: Raised if the number of mandatory arguments do not match """ user_args = inspect.getfullargspec(user_func).args # Drop the first argument if it's a bound method @@ -1503,7 +1449,7 @@ def check_fn_match_arg_spec( number_of_event_args = len(parsed_event_args) if number_of_user_args - number_of_user_default_args > number_of_event_args: - raise EventFnArgMismatch( + raise EventFnArgMismatchError( f"Event {key} only provides {number_of_event_args} arguments, but " f"{func_name or user_func} requires at least {number_of_user_args - number_of_user_default_args} " "arguments to be passed to the event handler.\n" @@ -1591,7 +1537,7 @@ def get_handler_args( def fix_events( - events: list[EventHandler | EventSpec] | None, + events: list[EventSpec | EventHandler] | None, token: str, router_data: dict[str, Any] | None = None, ) -> list[Event]: @@ -1631,7 +1577,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 = { @@ -1675,12 +1621,12 @@ class EventVar(ObjectVar, python_types=EventSpec): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) 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. @@ -1736,7 +1682,7 @@ class EventChainVar(BuilderFunctionVar, python_types=EventChain): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) # Note: LiteralVar is second in the inheritance list allowing it act like a # CachedVarOperation (ArgsFunctionOperation) and get the _js_expr from the @@ -1744,7 +1690,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. @@ -1768,13 +1714,16 @@ class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainV Returns: The created LiteralEventChainVar instance. + + Raises: + ValueError: If the invocation is not a FunctionVar. """ arg_spec = ( value.args_spec[0] 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]) @@ -1785,10 +1734,21 @@ class LiteralEventChainVar(ArgsFunctionOperationBuilder, LiteralVar, EventChainV arg_def_expr = Var(_js_expr="args") if value.invocation is None: - invocation = FunctionStringVar.create("addEvents") + invocation = FunctionStringVar.create( + CompileVars.ADD_EVENTS, + _var_data=VarData( + imports=Imports.EVENTS, + hooks={Hooks.EVENTS: None}, + ), + ) else: invocation = value.invocation + if invocation is not None and not isinstance(invocation, FunctionVar): + raise ValueError( + f"EventChain invocation must be a FunctionVar, got {invocation!s} of type {invocation._var_type!s}." + ) + return cls( _js_expr="", _var_type=EventChain, @@ -1812,8 +1772,6 @@ V3 = TypeVar("V3") V4 = TypeVar("V4") V5 = TypeVar("V5") -background_event_decorator = background - class EventCallback(Generic[P, T]): """A descriptor that wraps a function to be used as an event.""" @@ -1878,7 +1836,7 @@ class EventCallback(Generic[P, T]): 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: @@ -1887,17 +1845,17 @@ class EventCallback(Generic[P, T]): Returns: The function with the values. """ - return self.func(*values) # type: ignore + return self.func(*values) # pyright: ignore [reportCallIssue, reportReturnType] @overload def __get__( - self: EventCallback[P, T], instance: None, owner + self: EventCallback[P, T], instance: None, owner: Any ) -> EventCallback[P, T]: ... @overload - def __get__(self, instance, owner) -> Callable[P, T]: ... + def __get__(self, instance: Any, owner: Any) -> Callable[P, T]: ... - def __get__(self, instance, owner) -> Callable: # type: ignore + def __get__(self, instance: Any, owner: Any) -> Callable: """Get the function with the instance bound to it. Args: @@ -1908,9 +1866,9 @@ class EventCallback(Generic[P, T]): 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") @@ -1961,7 +1919,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 @@ -1986,6 +1944,9 @@ class EventNamespace(types.SimpleNamespace): func: The function to wrap. background: Whether the event should be run in the background. Defaults to False. + Raises: + TypeError: If background is True and the function is not a coroutine or async generator. # noqa: DAR402 + Returns: The wrapped function. """ @@ -1994,8 +1955,14 @@ class EventNamespace(types.SimpleNamespace): func: Callable[Concatenate[BASE_STATE, P], T], ) -> EventCallback[P, T]: if background is True: - return background_event_decorator(func, __internal_reflex_call=True) # type: ignore - return func # type: ignore + if not inspect.iscoroutinefunction( + func + ) and not inspect.isasyncgenfunction(func): + raise TypeError( + "Background task must be async function or generator." + ) + setattr(func, BACKGROUND_TASK_MARKER, True) + return func # pyright: ignore [reportReturnType] if func is not None: return wrapper(func) diff --git a/reflex/experimental/__init__.py b/reflex/experimental/__init__.py index 164790fe5..1a198f35a 100644 --- a/reflex/experimental/__init__.py +++ b/reflex/experimental/__init__.py @@ -9,7 +9,6 @@ from reflex.components.sonner.toast import toast as toast from ..utils.console import warn from . import hooks as hooks -from .assets import asset as asset from .client_state import ClientStateVar as ClientStateVar from .layout import layout as layout from .misc import run_in_thread as run_in_thread @@ -62,7 +61,6 @@ class ExperimentalNamespace(SimpleNamespace): _x = ExperimentalNamespace( - asset=asset, client_state=ClientStateVar.create, hooks=hooks, layout=layout, diff --git a/reflex/experimental/assets.py b/reflex/experimental/assets.py deleted file mode 100644 index e9be19aaf..000000000 --- a/reflex/experimental/assets.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Helper functions for adding assets to the app.""" - -from typing import Optional - -from reflex import assets -from reflex.utils import console - - -def asset(relative_filename: str, subfolder: Optional[str] = None) -> str: - """DEPRECATED: use `rx.asset` with `shared=True` instead. - - Add an asset to the app. - Place the file next to your including python file. - Copies the file to the app's external assets directory. - - Example: - ```python - rx.script(src=rx._x.asset("my_custom_javascript.js")) - rx.image(src=rx._x.asset("test_image.png","subfolder")) - ``` - - Args: - relative_filename: The relative filename of the asset. - subfolder: The directory to place the asset in. - - Returns: - The relative URL to the copied asset. - """ - console.deprecate( - feature_name="rx._x.asset", - reason="Use `rx.asset` with `shared=True` instead of `rx._x.asset`.", - deprecation_version="0.6.6", - removal_version="0.7.0", - ) - return assets.asset( - relative_filename, shared=True, subfolder=subfolder, _stack_level=2 - ) diff --git a/reflex/experimental/client_state.py b/reflex/experimental/client_state.py index 45dfef237..8138c2721 100644 --- a/reflex/experimental/client_state.py +++ b/reflex/experimental/client_state.py @@ -4,7 +4,6 @@ from __future__ import annotations import dataclasses import re -import sys from typing import Any, Callable, Union from reflex import constants @@ -34,10 +33,22 @@ def _client_state_ref(var_name: str) -> str: return f"refs['_client_state_{var_name}']" +def _client_state_ref_dict(var_name: str) -> str: + """Get the ref path for a ClientStateVar. + + Args: + var_name: The name of the variable. + + Returns: + An accessor for ClientStateVar ref as a string. + """ + return f"refs['_client_state_dict_{var_name}']" + + @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ClientStateVar(Var): """A Var that exists on the client via useState.""" @@ -115,10 +126,41 @@ class ClientStateVar(Var): "react": [ImportVar(tag="useState"), ImportVar(tag="useId")], } if global_ref: - hooks[f"{_client_state_ref(var_name)} ??= {{}}"] = None - hooks[f"{_client_state_ref(setter_name)} ??= {{}}"] = None - hooks[f"{_client_state_ref(var_name)}[{id_name}] = {var_name}"] = None - hooks[f"{_client_state_ref(setter_name)}[{id_name}] = {setter_name}"] = None + arg_name = get_unique_variable_name() + func = ArgsFunctionOperationBuilder.create( + args_names=(arg_name,), + return_expr=Var("Array.prototype.forEach.call") + .to(FunctionVar) + .call( + ( + Var("Object.values") + .to(FunctionVar) + .call(Var(_client_state_ref_dict(setter_name))) + .to(list) + .to(list) + ) + + Var.create( + [ + Var( + f"(value) => {{ {_client_state_ref(var_name)} = value; }}" + ) + ] + ).to(list), + ArgsFunctionOperationBuilder.create( + args_names=("setter",), + return_expr=Var("setter").to(FunctionVar).call(Var(arg_name)), + ), + ), + ) + + hooks[f"{_client_state_ref(setter_name)} = {func!s}"] = None + hooks[f"{_client_state_ref(var_name)} ??= {var_name!s}"] = None + hooks[f"{_client_state_ref_dict(var_name)} ??= {{}}"] = None + hooks[f"{_client_state_ref_dict(setter_name)} ??= {{}}"] = None + hooks[f"{_client_state_ref_dict(var_name)}[{id_name}] = {var_name}"] = None + hooks[ + f"{_client_state_ref_dict(setter_name)}[{id_name}] = {setter_name}" + ] = None imports.update(_refs_import) return cls( _js_expr="", @@ -150,7 +192,7 @@ class ClientStateVar(Var): return ( Var( _js_expr=( - _client_state_ref(self._getter_name) + f"[{self._id_name}]" + _client_state_ref_dict(self._getter_name) + f"[{self._id_name}]" if self._global_ref else self._getter_name ), @@ -158,9 +200,7 @@ class ClientStateVar(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 {}) ) ) @@ -179,26 +219,11 @@ class ClientStateVar(Var): """ _var_data = VarData(imports=_refs_import if self._global_ref else {}) - arg_name = get_unique_variable_name() setter = ( - ArgsFunctionOperationBuilder.create( - args_names=(arg_name,), - return_expr=Var("Array.prototype.forEach.call") - .to(FunctionVar) - .call( - Var("Object.values") - .to(FunctionVar) - .call(Var(_client_state_ref(self._setter_name))), - ArgsFunctionOperationBuilder.create( - args_names=("setter",), - return_expr=Var("setter").to(FunctionVar).call(Var(arg_name)), - ), - ), - _var_data=_var_data, - ) + Var(_client_state_ref(self._setter_name)) if self._global_ref - else Var(self._setter_name, _var_data=_var_data).to(FunctionVar) - ) + else Var(self._setter_name, _var_data=_var_data) + ).to(FunctionVar) if value is not NoValue: # This is a hack to make it work like an EventSpec taking an arg diff --git a/reflex/experimental/hooks.py b/reflex/experimental/hooks.py index 7d648225a..c00dd3bf9 100644 --- a/reflex/experimental/hooks.py +++ b/reflex/experimental/hooks.py @@ -11,7 +11,7 @@ def _compose_react_imports(tags: list[str]) -> dict[str, list[ImportVar]]: return {"react": [ImportVar(tag=tag) for tag in tags]} -def const(name, value) -> Var: +def const(name: str | list[str], value: str | Var) -> Var: """Create a constant Var. Args: @@ -26,7 +26,7 @@ def const(name, value) -> Var: return Var(_js_expr=f"const {name} = {value}") -def useCallback(func, deps) -> Var: +def useCallback(func: str, deps: list) -> Var: # noqa: N802 """Create a useCallback hook with a function and dependencies. Args: @@ -42,7 +42,7 @@ def useCallback(func, deps) -> Var: ) -def useContext(context) -> Var: +def useContext(context: str) -> Var: # noqa: N802 """Create a useContext hook with a context. Args: @@ -57,7 +57,7 @@ def useContext(context) -> Var: ) -def useRef(default) -> Var: +def useRef(default: str) -> Var: # noqa: N802 """Create a useRef hook with a default value. Args: @@ -72,7 +72,7 @@ def useRef(default) -> Var: ) -def useState(var_name, default=None) -> Var: +def useState(var_name: str, default: str | None = None) -> Var: # noqa: N802 """Create a useState hook with a variable name and setter name. Args: diff --git a/reflex/experimental/layout.py b/reflex/experimental/layout.py index e5a1bab04..d54e87f8b 100644 --- a/reflex/experimental/layout.py +++ b/reflex/experimental/layout.py @@ -12,6 +12,7 @@ from reflex.components.radix.themes.components.icon_button import IconButton from reflex.components.radix.themes.layout.box import Box from reflex.components.radix.themes.layout.container import Container from reflex.components.radix.themes.layout.stack import HStack +from reflex.constants.compiler import MemoizationMode from reflex.event import run_script from reflex.experimental import hooks from reflex.state import ComponentState @@ -44,10 +45,10 @@ class Sidebar(Box, MemoizationLeaf): 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") ) @@ -146,6 +147,8 @@ sidebar_trigger_style = { class SidebarTrigger(Fragment): """A component that renders the sidebar trigger.""" + _memoization_mode = MemoizationMode(recursive=False) + @classmethod def create(cls, sidebar: Component, **props): """Create the sidebar trigger component. @@ -159,11 +162,11 @@ class SidebarTrigger(Fragment): """ 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/experimental/layout.pyi b/reflex/experimental/layout.pyi index 4c7fc8d47..93c8c0137 100644 --- a/reflex/experimental/layout.pyi +++ b/reflex/experimental/layout.pyi @@ -109,7 +109,7 @@ class DrawerSidebar(DrawerRoot): snap_points: Optional[List[Union[float, str]]] = None, fade_from_index: Optional[Union[Var[int], int]] = None, scroll_lock_timeout: Optional[Union[Var[int], int]] = None, - preventScrollRestoration: Optional[Union[Var[bool], bool]] = None, + prevent_scroll_restoration: Optional[Union[Var[bool], bool]] = None, should_scale_background: Optional[Union[Var[bool], bool]] = None, close_threshold: Optional[Union[Var[float], float]] = None, as_child: Optional[Union[Var[bool], bool]] = None, diff --git a/reflex/experimental/misc.py b/reflex/experimental/misc.py index a2a5a0615..986729881 100644 --- a/reflex/experimental/misc.py +++ b/reflex/experimental/misc.py @@ -1,16 +1,16 @@ """Miscellaneous functions for the experimental package.""" import asyncio -from typing import Any +from typing import Any, Callable -async def run_in_thread(func) -> Any: +async def run_in_thread(func: Callable) -> Any: """Run a function in a separate thread. To not block the UI event queue, run_in_thread must be inside inside a rx.event(background=True) decorated method. Args: - func (callable): The non-async function to run. + func: The non-async function to run. Raises: ValueError: If the function is an async function. diff --git a/reflex/istate/wrappers.py b/reflex/istate/wrappers.py index d4e74cf8a..865bd6c63 100644 --- a/reflex/istate/wrappers.py +++ b/reflex/istate/wrappers.py @@ -6,7 +6,7 @@ from reflex.istate.proxy import ReadOnlyStateProxy from reflex.state import _split_substate_key, _substate_key, get_state_manager -async def get_state(token, state_cls: Any | None = None) -> ReadOnlyStateProxy: +async def get_state(token: str, state_cls: Any | None = None) -> ReadOnlyStateProxy: """Get the instance of a state for a token. Args: diff --git a/reflex/middleware/hydrate_middleware.py b/reflex/middleware/hydrate_middleware.py index 2198b82c2..2dea54e17 100644 --- a/reflex/middleware/hydrate_middleware.py +++ b/reflex/middleware/hydrate_middleware.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Optional from reflex import constants from reflex.event import Event, get_hydrate_event from reflex.middleware.middleware import Middleware -from reflex.state import BaseState, StateUpdate +from reflex.state import BaseState, StateUpdate, _resolve_delta if TYPE_CHECKING: from reflex.app import App @@ -42,7 +42,7 @@ class HydrateMiddleware(Middleware): setattr(state, constants.CompileVars.IS_HYDRATED, False) # Get the initial state. - delta = state.dict() + delta = await _resolve_delta(state.dict()) # since a full dict was captured, clean any dirtiness state._clean() diff --git a/reflex/model.py b/reflex/model.py index 295159de0..06bb87b02 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -18,6 +18,7 @@ import sqlalchemy import sqlalchemy.exc import sqlalchemy.ext.asyncio import sqlalchemy.orm +from alembic.runtime.migration import MigrationContext from reflex.base import Base from reflex.config import environment, get_config @@ -242,7 +243,7 @@ class ModelRegistry: 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. @@ -261,7 +262,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue super().__init_subclass__() @classmethod - def _dict_recursive(cls, value): + def _dict_recursive(cls, value: Any): """Recursively serialize the relationship object(s). Args: @@ -393,7 +394,11 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue writer = alembic.autogenerate.rewriter.Rewriter() @writer.rewrites(alembic.operations.ops.AddColumnOp) - def render_add_column_with_server_default(context, revision, op): + def render_add_column_with_server_default( + context: MigrationContext, + revision: str | None, + op: Any, + ): # Carry the sqlmodel default as server_default so that newly added # columns get the desired default value in existing rows. if op.column.default is not None and op.column.server_default is None: @@ -402,7 +407,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue ) return op - def run_autogenerate(rev, context): + def run_autogenerate(rev: str, context: MigrationContext): revision_context.run_autogenerate(rev, context) return [] @@ -415,7 +420,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue 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 ) @@ -444,7 +449,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue """ config, script_directory = cls._alembic_config() - def run_upgrade(rev, context): + def run_upgrade(rev: str, context: MigrationContext): return script_directory._upgrade_revs(to_rev, rev) with alembic.runtime.environment.EnvironmentContext( diff --git a/reflex/page.py b/reflex/page.py index 44ca6ab31..5f118aad1 100644 --- a/reflex/page.py +++ b/reflex/page.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections import defaultdict -from typing import Any, Dict, List +from typing import Any, Callable, Dict, List from reflex.config import get_config from reflex.event import BASE_STATE, EventType @@ -42,7 +42,7 @@ def page( The decorated function. """ - def decorator(render_fn): + def decorator(render_fn: Callable): kwargs = {} if route: kwargs["route"] = route @@ -66,7 +66,7 @@ def page( return decorator -def get_decorated_pages(omit_implicit_routes=True) -> list[dict[str, Any]]: +def get_decorated_pages(omit_implicit_routes: bool = True) -> list[dict[str, Any]]: """Get the decorated pages. Args: diff --git a/reflex/reflex.py b/reflex/reflex.py index b0f4ccd91..d1e565665 100644 --- a/reflex/reflex.py +++ b/reflex/reflex.py @@ -17,7 +17,7 @@ from reflex.state import reset_disk_state_manager 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: @@ -125,8 +125,8 @@ def _run( env: constants.Env = constants.Env.DEV, frontend: bool = True, backend: bool = True, - frontend_port: str = str(config.frontend_port), - backend_port: str = str(config.backend_port), + frontend_port: int = config.frontend_port, + backend_port: int = config.backend_port, backend_host: str = config.backend_host, loglevel: constants.LogLevel = config.loglevel, ): @@ -160,18 +160,22 @@ def _run( # Find the next available open port if applicable. if frontend: frontend_port = processes.handle_port( - "frontend", frontend_port, str(constants.DefaultPorts.FRONTEND_PORT) + "frontend", + frontend_port, + constants.DefaultPorts.FRONTEND_PORT, ) if backend: backend_port = processes.handle_port( - "backend", backend_port, str(constants.DefaultPorts.BACKEND_PORT) + "backend", + backend_port, + constants.DefaultPorts.BACKEND_PORT, ) # Apply the new ports to the config. - if frontend_port != str(config.frontend_port): + if frontend_port != config.frontend_port: config._set_persistent(frontend_port=frontend_port) - if backend_port != str(config.backend_port): + if backend_port != config.backend_port: config._set_persistent(backend_port=backend_port) # Reload the config to make sure the env vars are persistent. @@ -262,10 +266,10 @@ def run( help="Execute only backend.", envvar=environment.REFLEX_BACKEND_ONLY.name, ), - frontend_port: str = typer.Option( + frontend_port: int = typer.Option( config.frontend_port, help="Specify a different frontend port." ), - backend_port: str = typer.Option( + backend_port: int = typer.Option( config.backend_port, help="Specify a different backend port." ), backend_host: str = typer.Option( @@ -306,6 +310,9 @@ def export( help="Whether to exclude sqlite db files when exporting backend.", hidden=True, ), + env: constants.Env = typer.Option( + constants.Env.PROD, help="The environment to export the app in." + ), loglevel: constants.LogLevel = typer.Option( config.loglevel, help="The log level to use." ), @@ -323,6 +330,7 @@ def export( backend=backend, zip_dest_dir=zip_dest_dir, upload_db_file=upload_db_file, + env=env, loglevel=loglevel.subprocess_level(), ) @@ -351,7 +359,7 @@ def logout( check_version() - logout(loglevel) # type: ignore + logout(loglevel) # pyright: ignore [reportArgumentType] db_cli = typer.Typer() @@ -440,7 +448,11 @@ def deploy( config.app_name, "--app-name", help="The name of the App to deploy under.", - hidden=True, + ), + app_id: str = typer.Option( + None, + "--app-id", + help="The ID of the App to deploy over.", ), regions: List[str] = typer.Option( [], @@ -480,6 +492,11 @@ def deploy( "--project", help="project id to deploy to", ), + project_name: Optional[str] = typer.Option( + None, + "--project-name", + help="The name of the project to deploy to.", + ), token: Optional[str] = typer.Option( None, "--token", @@ -492,6 +509,7 @@ def deploy( ), ): """Deploy the app to the Reflex hosting service.""" + from reflex_cli.constants.base import LogLevel as HostingLogLevel from reflex_cli.utils import dependency from reflex_cli.v2 import cli as hosting_cli @@ -503,12 +521,20 @@ def deploy( # Set the log level. console.set_log_level(loglevel) - if not token: - # make sure user is logged in. - if interactive: - hosting_cli.login() - else: - raise SystemExit("Token is required for non-interactive mode.") + def convert_reflex_loglevel_to_reflex_cli_loglevel( + loglevel: constants.LogLevel, + ) -> HostingLogLevel: + if loglevel == constants.LogLevel.DEBUG: + return HostingLogLevel.DEBUG + if loglevel == constants.LogLevel.INFO: + return HostingLogLevel.INFO + if loglevel == constants.LogLevel.WARNING: + return HostingLogLevel.WARNING + if loglevel == constants.LogLevel.ERROR: + return HostingLogLevel.ERROR + if loglevel == constants.LogLevel.CRITICAL: + return HostingLogLevel.CRITICAL + return HostingLogLevel.INFO # Only check requirements if interactive. # There is user interaction for requirements update. @@ -519,11 +545,10 @@ def deploy( if prerequisites.needs_reinit(frontend=True): _init(name=config.app_name, loglevel=loglevel) prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME) - extra: dict[str, str] = ( - {"config_path": config_path} if config_path is not None else {} - ) + hosting_cli.deploy( app_name=app_name, + app_id=app_id, export_fn=lambda zip_dest_dir, api_url, deploy_url, @@ -544,13 +569,28 @@ def deploy( envfile=envfile, hostname=hostname, interactive=interactive, - loglevel=type(loglevel).INFO, # type: ignore + loglevel=convert_reflex_loglevel_to_reflex_cli_loglevel(loglevel), token=token, project=project, - **extra, + project_name=project_name, + **({"config_path": config_path} if config_path is not None else {}), ) +@cli.command() +def rename( + new_name: str = typer.Argument(..., help="The new name for the app."), + loglevel: constants.LogLevel = typer.Option( + config.loglevel, help="The log level to use." + ), +): + """Rename the app in the current directory.""" + from reflex.utils import prerequisites + + prerequisites.validate_app_name(new_name) + prerequisites.rename_app(new_name, loglevel) + + cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.") cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.") cli.add_typer( diff --git a/reflex/route.py b/reflex/route.py index 0b7172824..3f49f66e9 100644 --- a/reflex/route.py +++ b/reflex/route.py @@ -103,7 +103,7 @@ def catchall_prefix(route: str) -> str: return route.replace(pattern, "") if pattern else "" -def replace_brackets_with_keywords(input_string): +def replace_brackets_with_keywords(input_string: str) -> str: """Replace brackets and everything inside it in a string with a keyword. Args: diff --git a/reflex/state.py b/reflex/state.py index e15c73978..92aaa4710 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -15,7 +15,6 @@ import time import typing import uuid from abc import ABC, abstractmethod -from collections import defaultdict from hashlib import md5 from pathlib import Path from types import FunctionType, MethodType @@ -31,6 +30,7 @@ from typing import ( Optional, Sequence, Set, + SupportsIndex, Tuple, Type, TypeVar, @@ -93,14 +93,14 @@ from reflex.event import ( ) from reflex.utils import console, format, path_ops, prerequisites, types from reflex.utils.exceptions import ( - ComputedVarShadowsBaseVars, - ComputedVarShadowsStateVar, - DynamicComponentInvalidSignature, - DynamicRouteArgShadowsStateVar, - EventHandlerShadowsBuiltInStateMethod, + ComputedVarShadowsBaseVarsError, + ComputedVarShadowsStateVarError, + DynamicComponentInvalidSignatureError, + DynamicRouteArgShadowsStateVarError, + EventHandlerShadowsBuiltInStateMethodError, ImmutableStateError, InvalidLockWarningThresholdError, - InvalidStateManagerMode, + InvalidStateManagerModeError, LockExpiredError, ReflexRuntimeError, SetUndefinedStateVarError, @@ -328,6 +328,25 @@ def get_var_for_field(cls: Type[BaseState], f: ModelField): ) +async def _resolve_delta(delta: Delta) -> Delta: + """Await all coroutines in the delta. + + Args: + delta: The delta to process. + + Returns: + The same delta dict with all coroutines resolved to their return value. + """ + tasks = {} + for state_name, state_delta in delta.items(): + for var_name, value in state_delta.items(): + if asyncio.iscoroutine(value): + tasks[state_name, var_name] = asyncio.create_task(value) + for (state_name, var_name), task in tasks.items(): + delta[state_name][var_name] = await task + return delta + + class BaseState(Base, ABC, extra=pydantic.Extra.allow): """The state of the app.""" @@ -355,11 +374,8 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): # A set of subclassses of this class. class_subclasses: ClassVar[Set[Type[BaseState]]] = set() - # Mapping of var name to set of computed variables that depend on it - _computed_var_dependencies: ClassVar[Dict[str, Set[str]]] = {} - - # Mapping of var name to set of substates that depend on it - _substate_var_dependencies: ClassVar[Dict[str, Set[str]]] = {} + # Mapping of var name to set of (state_full_name, var_name) that depend on it. + _var_dependencies: ClassVar[Dict[str, Set[Tuple[str, str]]]] = {} # Set of vars which always need to be recomputed _always_dirty_computed_vars: ClassVar[Set[str]] = set() @@ -367,6 +383,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): # Set of substates which always need to be recomputed _always_dirty_substates: ClassVar[Set[str]] = set() + # Set of states which might need to be recomputed if vars in this state change. + _potentially_dirty_states: ClassVar[Set[str]] = set() + # The parent state. parent_state: Optional[BaseState] = None @@ -518,6 +537,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): # Reset dirty substate tracking for this class. cls._always_dirty_substates = set() + cls._potentially_dirty_states = set() # Get the parent vars. parent_state = cls.get_parent_state() @@ -587,7 +607,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): 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 +619,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): 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: @@ -621,8 +641,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): setattr(cls, name, handler) # Initialize per-class var dependency tracking. - cls._computed_var_dependencies = defaultdict(set) - cls._substate_var_dependencies = defaultdict(set) + cls._var_dependencies = {} cls._init_var_dependency_dicts() @staticmethod @@ -767,26 +786,27 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): Additional updates tracking dicts for vars and substates that always need to be recomputed. """ - inherited_vars = set(cls.inherited_vars).union( - set(cls.inherited_backend_vars), - ) for cvar_name, cvar in cls.computed_vars.items(): - # Add the dependencies. - for var in cvar._deps(objclass=cls): - cls._computed_var_dependencies[var].add(cvar_name) - if var in inherited_vars: - # track that this substate depends on its parent for this var - state_name = cls.get_name() - parent_state = cls.get_parent_state() - while parent_state is not None and var in { - **parent_state.vars, - **parent_state.backend_vars, + if not cvar._cache: + # Do not perform dep calculation when cache=False (these are always dirty). + continue + for state_name, dvar_set in cvar._deps(objclass=cls).items(): + state_cls = cls.get_root_state().get_class_substate(state_name) + for dvar in dvar_set: + defining_state_cls = state_cls + while dvar in { + *defining_state_cls.inherited_vars, + *defining_state_cls.inherited_backend_vars, }: - parent_state._substate_var_dependencies[var].add(state_name) - state_name, parent_state = ( - parent_state.get_name(), - parent_state.get_parent_state(), - ) + parent_state = defining_state_cls.get_parent_state() + if parent_state is not None: + defining_state_cls = parent_state + defining_state_cls._var_dependencies.setdefault(dvar, set()).add( + (cls.get_full_name(), cvar_name) + ) + defining_state_cls._potentially_dirty_states.add( + cls.get_full_name() + ) # ComputedVar with cache=False always need to be recomputed cls._always_dirty_computed_vars = { @@ -815,7 +835,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """Check for shadow methods and raise error if any. Raises: - EventHandlerShadowsBuiltInStateMethod: When an event handler shadows an inbuilt state method. + EventHandlerShadowsBuiltInStateMethodError: When an event handler shadows an inbuilt state method. """ overridden_methods = set() state_base_functions = cls._get_base_functions() @@ -829,7 +849,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): overridden_methods.add(method.__name__) for method_name in overridden_methods: - raise EventHandlerShadowsBuiltInStateMethod( + raise EventHandlerShadowsBuiltInStateMethodError( f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead" ) @@ -838,11 +858,11 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """Check for shadow base vars and raise error if any. Raises: - ComputedVarShadowsBaseVars: When a computed var shadows a base var. + ComputedVarShadowsBaseVarsError: When a computed var shadows a base var. """ for computed_var_ in cls._get_computed_vars(): if computed_var_._js_expr in cls.__annotations__: - raise ComputedVarShadowsBaseVars( + raise ComputedVarShadowsBaseVarsError( f"The computed var name `{computed_var_._js_expr}` shadows a base var in {cls.__module__}.{cls.__name__}; use a different name instead" ) @@ -851,14 +871,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """Check for shadow computed vars and raise error if any. Raises: - ComputedVarShadowsStateVar: When a computed var shadows another. + ComputedVarShadowsStateVarError: When a computed var shadows another. """ for name, cv in cls.__dict__.items(): if not is_computed_var(cv): continue name = cv._js_expr if name in cls.inherited_vars or name in cls.inherited_backend_vars: - raise ComputedVarShadowsStateVar( + raise ComputedVarShadowsStateVarError( f"The computed var name `{cv._js_expr}` shadows a var in {cls.__module__}.{cls.__name__}; use a different name instead" ) @@ -899,7 +919,18 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): ] 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 + @functools.lru_cache() + def get_root_state(cls) -> Type[BaseState]: + """Get the root state. + + Returns: + The root state. + """ + parent_state = cls.get_parent_state() + return cls if parent_state is None else parent_state.get_root_state() @classmethod def get_substates(cls) -> set[Type[BaseState]]: @@ -1058,7 +1089,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): setattr(cls, prop._var_field_name, prop) @classmethod - def _create_event_handler(cls, fn): + def _create_event_handler(cls, fn: Any): """Create an event handler for the given function. Args: @@ -1176,14 +1207,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): cls._check_overwritten_dynamic_args(list(args.keys())) - def argsingle_factory(param): - def inner_func(self) -> str: + def argsingle_factory(param: str): + def inner_func(self: BaseState) -> str: return self.router.page.params.get(param, "") return inner_func - def arglist_factory(param): - def inner_func(self) -> List[str]: + def arglist_factory(param: str): + def inner_func(self: BaseState) -> List[str]: return self.router.page.params.get(param, []) return inner_func @@ -1218,14 +1249,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): args: a dict of args Raises: - DynamicRouteArgShadowsStateVar: If a dynamic arg is shadowing an existing var. + DynamicRouteArgShadowsStateVarError: If a dynamic arg is shadowing an existing var. """ for arg in args: if ( arg in cls.computed_vars and not isinstance(cls.computed_vars[arg], DynamicRouteVar) ) or arg in cls.base_vars: - raise DynamicRouteArgShadowsStateVar( + raise DynamicRouteArgShadowsStateVarError( f"Dynamic route arg '{arg}' is shadowing an existing var in {cls.__module__}.{cls.__name__}" ) for substate in cls.get_substates(): @@ -1268,8 +1299,8 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): 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") @@ -1341,19 +1372,16 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): if field.allow_none and not is_optional(field_type): field_type = Union[field_type, None] if not _isinstance(value, field_type): - console.deprecate( - "mismatched-type-assignment", - f"Tried to assign value {value} of type {type(value)} to field {type(self).__name__}.{name} of type {field_type}." - " This might lead to unexpected behavior.", - "0.6.5", - "0.7.0", + console.error( + f"Expected field '{type(self).__name__}.{name}' to receive type '{field_type}'," + f" but got '{value}' of type '{type(value)}'." ) # Set the attribute. super().__setattr__(name, value) # Add the var to the dirty list. - if name in self.vars or name in self._computed_var_dependencies: + if name in self.base_vars: self.dirty_vars.add(name) self._mark_dirty() @@ -1424,63 +1452,21 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): return self.substates[path[0]].get_substate(path[1:]) @classmethod - def _get_common_ancestor(cls, other: Type[BaseState]) -> str: - """Find the name of the nearest common ancestor shared by this and the other state. - - Args: - other: The other state. + def _get_potentially_dirty_states(cls) -> set[type[BaseState]]: + """Get substates which may have dirty vars due to dependencies. Returns: - Full name of the nearest common ancestor. + The set of potentially dirty substate classes. """ - common_ancestor_parts = [] - for part1, part2 in zip( - cls.get_full_name().split("."), - other.get_full_name().split("."), - ): - if part1 != part2: - break - common_ancestor_parts.append(part1) - return ".".join(common_ancestor_parts) - - @classmethod - def _determine_missing_parent_states( - cls, target_state_cls: Type[BaseState] - ) -> tuple[str, list[str]]: - """Determine the missing parent states between the target_state_cls and common ancestor of this state. - - Args: - target_state_cls: The class of the state to find missing parent states for. - - Returns: - The name of the common ancestor and the list of missing parent states. - """ - common_ancestor_name = cls._get_common_ancestor(target_state_cls) - common_ancestor_parts = common_ancestor_name.split(".") - target_state_parts = tuple(target_state_cls.get_full_name().split(".")) - relative_target_state_parts = target_state_parts[len(common_ancestor_parts) :] - - # Determine which parent states to fetch from the common ancestor down to the target_state_cls. - fetch_parent_states = [common_ancestor_name] - for relative_parent_state_name in relative_target_state_parts: - fetch_parent_states.append( - ".".join((fetch_parent_states[-1], relative_parent_state_name)) - ) - - return common_ancestor_name, fetch_parent_states[1:-1] - - def _get_parent_states(self) -> list[tuple[str, BaseState]]: - """Get all parent state instances up to the root of the state tree. - - Returns: - A list of tuples containing the name and the instance of each parent state. - """ - parent_states_with_name = [] - parent_state = self - while parent_state.parent_state is not None: - parent_state = parent_state.parent_state - parent_states_with_name.append((parent_state.get_full_name(), parent_state)) - return parent_states_with_name + return { + cls.get_class_substate(substate_name) + for substate_name in cls._always_dirty_substates + }.union( + { + cls.get_root_state().get_class_substate(substate_name) + for substate_name in cls._potentially_dirty_states + } + ) def _get_root_state(self) -> BaseState: """Get the root state of the state tree. @@ -1493,55 +1479,38 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): parent_state = parent_state.parent_state return parent_state - async def _populate_parent_states(self, target_state_cls: Type[BaseState]): - """Populate substates in the tree between the target_state_cls and common ancestor of this state. + async def _get_state_from_redis(self, state_cls: Type[T_STATE]) -> T_STATE: + """Get a state instance from redis. Args: - target_state_cls: The class of the state to populate parent states for. + state_cls: The class of the state. Returns: - The parent state instance of target_state_cls. + The instance of state_cls associated with this state's client_token. Raises: RuntimeError: If redis is not used in this backend process. + StateMismatchError: If the state instance is not of the expected type. """ + # Then get the target state and all its substates. state_manager = get_state_manager() if not isinstance(state_manager, StateManagerRedis): raise RuntimeError( - f"Cannot populate parent states of {target_state_cls.get_full_name()} without redis. " + f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. " "(All states should already be available -- this is likely a bug).", ) + state_in_redis = await state_manager.get_state( + token=_substate_key(self.router.session.client_token, state_cls), + top_level=False, + for_state_instance=self, + ) - # Find the missing parent states up to the common ancestor. - ( - common_ancestor_name, - missing_parent_states, - ) = self._determine_missing_parent_states(target_state_cls) - - # Fetch all missing parent states and link them up to the common ancestor. - parent_states_tuple = self._get_parent_states() - root_state = parent_states_tuple[-1][1] - parent_states_by_name = dict(parent_states_tuple) - parent_state = parent_states_by_name[common_ancestor_name] - for parent_state_name in missing_parent_states: - try: - parent_state = root_state.get_substate(parent_state_name.split(".")) - # The requested state is already cached, do NOT fetch it again. - continue - except ValueError: - # The requested state is missing, fetch from redis. - pass - parent_state = await state_manager.get_state( - token=_substate_key( - self.router.session.client_token, parent_state_name - ), - top_level=False, - get_substates=False, - parent_state=parent_state, + if not isinstance(state_in_redis, state_cls): + raise StateMismatchError( + f"Searched for state {state_cls.get_full_name()} but found {state_in_redis}." ) - # Return the direct parent of target_state_cls for subsequent linking. - return parent_state + return state_in_redis def _get_state_from_cache(self, state_cls: Type[T_STATE]) -> T_STATE: """Get a state instance from the cache. @@ -1563,44 +1532,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): ) return substate - async def _get_state_from_redis(self, state_cls: Type[T_STATE]) -> T_STATE: - """Get a state instance from redis. - - Args: - state_cls: The class of the state. - - Returns: - The instance of state_cls associated with this state's client_token. - - Raises: - RuntimeError: If redis is not used in this backend process. - StateMismatchError: If the state instance is not of the expected type. - """ - # Fetch all missing parent states from redis. - parent_state_of_state_cls = await self._populate_parent_states(state_cls) - - # Then get the target state and all its substates. - state_manager = get_state_manager() - if not isinstance(state_manager, StateManagerRedis): - raise RuntimeError( - f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. " - "(All states should already be available -- this is likely a bug).", - ) - - state_in_redis = await state_manager.get_state( - token=_substate_key(self.router.session.client_token, state_cls), - top_level=False, - get_substates=True, - parent_state=parent_state_of_state_cls, - ) - - if not isinstance(state_in_redis, state_cls): - raise StateMismatchError( - f"Searched for state {state_cls.get_full_name()} but found {state_in_redis}." - ) - - return state_in_redis - async def get_state(self, state_cls: Type[T_STATE]) -> T_STATE: """Get an instance of the state associated with this token. @@ -1636,11 +1567,13 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """ # 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 + + unset = object() # Fast case: this is a literal var and the value is known. - if hasattr(var, "_var_value"): - return var._var_value + if (var_value := getattr(var, "_var_value", unset)) is not unset: + return var_value # pyright: ignore [reportReturnType] var_data = var._get_all_var_data() if var_data is None or not var_data.state: @@ -1737,7 +1670,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`)" ) - def _as_state_update( + async def _as_state_update( self, handler: EventHandler, events: EventSpec | list[EventSpec] | None, @@ -1765,7 +1698,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): try: # Get the delta after processing the event. - delta = state.get_delta() + delta = await _resolve_delta(state.get_delta()) state._clean() return StateUpdate( @@ -1776,9 +1709,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): except Exception as ex: state._clean() - app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP) - - event_specs = app_instance.backend_exception_handler(ex) + event_specs = ( + prerequisites.get_and_validate_app().app.backend_exception_handler(ex) + ) if event_specs is None: return StateUpdate() @@ -1831,7 +1764,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): if ( isinstance(value, dict) and inspect.isclass(hinted_args) - and not types.is_generic_alias(hinted_args) # py3.9-py3.10 + and not types.is_generic_alias(hinted_args) # py3.10 ): if issubclass(hinted_args, Model): # Remove non-fields from the payload @@ -1865,34 +1798,38 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): # Handle async generators. if inspect.isasyncgen(events): async for event in events: - yield state._as_state_update(handler, event, final=False) - yield state._as_state_update(handler, events=None, final=True) + yield await state._as_state_update(handler, event, final=False) + yield await state._as_state_update(handler, events=None, final=True) # Handle regular generators. elif inspect.isgenerator(events): try: while True: - yield state._as_state_update(handler, next(events), final=False) + yield await state._as_state_update( + handler, next(events), final=False + ) except StopIteration as si: # the "return" value of the generator is not available # in the loop, we must catch StopIteration to access it if si.value is not None: - yield state._as_state_update(handler, si.value, final=False) - yield state._as_state_update(handler, events=None, final=True) + yield await state._as_state_update( + handler, si.value, final=False + ) + yield await state._as_state_update(handler, events=None, final=True) # Handle regular event chains. else: - yield state._as_state_update(handler, events, final=True) + yield await state._as_state_update(handler, events, final=True) # If an error occurs, throw a window alert. except Exception as ex: telemetry.send_error(ex, context="backend") - app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP) + event_specs = ( + prerequisites.get_and_validate_app().app.backend_exception_handler(ex) + ) - event_specs = app_instance.backend_exception_handler(ex) - - yield state._as_state_update( + yield await state._as_state_update( handler, event_specs, final=True, @@ -1900,15 +1837,28 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): def _mark_dirty_computed_vars(self) -> None: """Mark ComputedVars that need to be recalculated based on dirty_vars.""" + # Append expired computed vars to dirty_vars to trigger recalculation + self.dirty_vars.update(self._expired_computed_vars()) + # Append always dirty computed vars to dirty_vars to trigger recalculation + self.dirty_vars.update(self._always_dirty_computed_vars) + dirty_vars = self.dirty_vars while dirty_vars: calc_vars, dirty_vars = dirty_vars, set() - for cvar in self._dirty_computed_vars(from_vars=calc_vars): - self.dirty_vars.add(cvar) + for state_name, cvar in self._dirty_computed_vars(from_vars=calc_vars): + if state_name == self.get_full_name(): + defining_state = self + else: + defining_state = self._get_root_state().get_substate( + tuple(state_name.split(".")) + ) + defining_state.dirty_vars.add(cvar) dirty_vars.add(cvar) - actual_var = self.computed_vars.get(cvar) + actual_var = defining_state.computed_vars.get(cvar) if actual_var is not None: - actual_var.mark_dirty(instance=self) + actual_var.mark_dirty(instance=defining_state) + if defining_state is not self: + defining_state._mark_dirty() def _expired_computed_vars(self) -> set[str]: """Determine ComputedVars that need to be recalculated based on the expiration time. @@ -1924,7 +1874,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): def _dirty_computed_vars( self, from_vars: set[str] | None = None, include_backend: bool = True - ) -> set[str]: + ) -> set[tuple[str, str]]: """Determine ComputedVars that need to be recalculated based on the given vars. Args: @@ -1935,33 +1885,12 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): Set of computed vars to include in the delta. """ return { - cvar + (state_name, cvar) for dirty_var in from_vars or self.dirty_vars - for cvar in self._computed_var_dependencies[dirty_var] + for state_name, cvar in self._var_dependencies.get(dirty_var, set()) if include_backend or not self.computed_vars[cvar]._backend } - @classmethod - def _potentially_dirty_substates(cls) -> set[Type[BaseState]]: - """Determine substates which could be affected by dirty vars in this state. - - Returns: - Set of State classes that may need to be fetched to recalc computed vars. - """ - # _always_dirty_substates need to be fetched to recalc computed vars. - fetch_substates = { - cls.get_class_substate((cls.get_name(), *substate_name.split("."))) - for substate_name in cls._always_dirty_substates - } - for dependent_substates in cls._substate_var_dependencies.values(): - fetch_substates.update( - { - cls.get_class_substate((cls.get_name(), *substate_name.split("."))) - for substate_name in dependent_substates - } - ) - return fetch_substates - def get_delta(self) -> Delta: """Get the delta for the state. @@ -1970,21 +1899,15 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): """ delta = {} - # Apply dirty variables down into substates - self.dirty_vars.update(self._always_dirty_computed_vars) - self._mark_dirty() - + self._mark_dirty_computed_vars() frontend_computed_vars: set[str] = { name for name, cv in self.computed_vars.items() if not cv._backend } # Return the dirty vars for this instance, any cached/dependent computed vars, # and always dirty computed vars (cache=False) - delta_vars = ( - self.dirty_vars.intersection(self.base_vars) - .union(self.dirty_vars.intersection(frontend_computed_vars)) - .union(self._dirty_computed_vars(include_backend=False)) - .union(self._always_dirty_computed_vars) + delta_vars = self.dirty_vars.intersection(self.base_vars).union( + self.dirty_vars.intersection(frontend_computed_vars) ) subdelta: Dict[str, Any] = { @@ -2014,23 +1937,9 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): self.parent_state.dirty_substates.add(self.get_name()) self.parent_state._mark_dirty() - # Append expired computed vars to dirty_vars to trigger recalculation - self.dirty_vars.update(self._expired_computed_vars()) - # have to mark computed vars dirty to allow access to newly computed # values within the same ComputedVar function self._mark_dirty_computed_vars() - self._mark_dirty_substates() - - def _mark_dirty_substates(self): - """Propagate dirty var / computed var status into substates.""" - substates = self.substates - for var in self.dirty_vars: - for substate_name in self._substate_var_dependencies[var]: - self.dirty_substates.add(substate_name) - substate = substates[substate_name] - substate.dirty_vars.add(var) - substate._mark_dirty() def _update_was_touched(self): """Update the _was_touched flag based on dirty_vars.""" @@ -2102,11 +2011,7 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): The object as a dictionary. """ if include_computed: - # Apply dirty variables down into substates to allow never-cached ComputedVar to - # trigger recalculation of dependent vars - self.dirty_vars.update(self._always_dirty_computed_vars) - self._mark_dirty() - + self._mark_dirty_computed_vars() base_vars = { prop_name: self.get_value(prop_name) for prop_name in self.base_vars } @@ -2356,8 +2261,7 @@ def dynamic(func: Callable[[T], Component]): The dynamically generated component. Raises: - DynamicComponentInvalidSignature: If the function does not have exactly one parameter. - DynamicComponentInvalidSignature: If the function does not have a type hint for the state class. + DynamicComponentInvalidSignatureError: If the function does not have exactly one parameter or a type hint for the state class. """ number_of_parameters = len(inspect.signature(func).parameters) @@ -2369,12 +2273,12 @@ def dynamic(func: Callable[[T], Component]): values = list(func_signature.values()) if number_of_parameters != 1: - raise DynamicComponentInvalidSignature( + raise DynamicComponentInvalidSignatureError( "The function must have exactly one parameter, which is the state class." ) if len(values) != 1: - raise DynamicComponentInvalidSignature( + raise DynamicComponentInvalidSignatureError( "You must provide a type hint for the state class in the function." ) @@ -2403,8 +2307,9 @@ class FrontendEventExceptionState(State): component_stack: The stack trace of the component where the exception occurred. """ - app_instance = getattr(prerequisites.get_app(), constants.CompileVars.APP) - app_instance.frontend_exception_handler(Exception(stack)) + prerequisites.get_and_validate_app().app.frontend_exception_handler( + Exception(stack) + ) class UpdateVarsInternalState(State): @@ -2442,19 +2347,20 @@ class OnLoadInternalState(State): The list of events to queue for on load handling. """ # Do not app._compile()! It should be already compiled by now. - app = getattr(prerequisites.get_app(), constants.CompileVars.APP) - load_events = app.get_load_events(self.router.page.path) + load_events = prerequisites.get_and_validate_app().app.get_load_events( + self.router.page.path + ) if not load_events: self.is_hydrated = True return # Fast path for navigation with no on_load events defined. self.is_hydrated = False return [ *fix_events( - load_events, + cast(list[Union[EventSpec, EventHandler]], load_events), 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] ] @@ -2595,7 +2501,9 @@ class StateProxy(wrapt.ObjectProxy): """ def __init__( - self, state_instance, parent_state_proxy: Optional["StateProxy"] = None + self, + state_instance: BaseState, + parent_state_proxy: Optional["StateProxy"] = None, ): """Create a proxy for a state instance. @@ -2609,7 +2517,7 @@ class StateProxy(wrapt.ObjectProxy): """ super().__init__(state_instance) # compile is not relevant to backend logic - self._self_app = getattr(prerequisites.get_app(), constants.CompileVars.APP) + self._self_app = prerequisites.get_and_validate_app().app self._self_substate_path = tuple(state_instance.get_full_name().split(".")) self._self_actx = None self._self_mutable = False @@ -2738,7 +2646,7 @@ class StateProxy(wrapt.ObjectProxy): # 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__: @@ -2751,7 +2659,7 @@ class StateProxy(wrapt.ObjectProxy): ) 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: @@ -2820,7 +2728,7 @@ class StateProxy(wrapt.ObjectProxy): await self.__wrapped__.get_state(state_cls), parent_state_proxy=self ) - def _as_state_update(self, *args, **kwargs) -> StateUpdate: + async def _as_state_update(self, *args, **kwargs) -> StateUpdate: """Temporarily allow mutability to access parent_state. Args: @@ -2833,7 +2741,7 @@ class StateProxy(wrapt.ObjectProxy): original_mutable = self._self_mutable self._self_mutable = True try: - return self.__wrapped__._as_state_update(*args, **kwargs) + return await self.__wrapped__._as_state_update(*args, **kwargs) finally: self._self_mutable = original_mutable @@ -2876,7 +2784,7 @@ class StateManager(Base, ABC): state: The state class to use. Raises: - InvalidStateManagerMode: If the state manager mode is invalid. + InvalidStateManagerModeError: If the state manager mode is invalid. Returns: The state manager (either disk, memory or redis). @@ -2899,7 +2807,7 @@ class StateManager(Base, ABC): lock_expiration=config.redis_lock_expiration, lock_warning_threshold=config.redis_lock_warning_threshold, ) - raise InvalidStateManagerMode( + raise InvalidStateManagerModeError( f"Expected one of: DISK, MEMORY, REDIS, got {config.state_manager_mode}" ) @@ -2951,7 +2859,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 = { @@ -3048,7 +2956,7 @@ def is_serializable(value: Any) -> bool: def reset_disk_state_manager(): """Reset the disk state manager.""" - states_directory = prerequisites.get_web_dir() / constants.Dirs.STATES + states_directory = prerequisites.get_states_dir() if states_directory.exists(): for path in states_directory.iterdir(): path.unlink() @@ -3069,7 +2977,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 = { @@ -3096,7 +3004,7 @@ class StateManagerDisk(StateManager): Returns: The states directory. """ - return prerequisites.get_web_dir() / constants.Dirs.STATES + return prerequisites.get_states_dir() def _purge_expired_states(self): """Purge expired states from the disk.""" @@ -3309,103 +3217,106 @@ class StateManagerRedis(StateManager): b"evicted", } - async def _get_parent_state( - self, token: str, state: BaseState | None = None - ) -> BaseState | None: - """Get the parent state for the state requested in the token. + def _get_required_state_classes( + self, + target_state_cls: Type[BaseState], + subclasses: bool = False, + required_state_classes: set[Type[BaseState]] | None = None, + ) -> set[Type[BaseState]]: + """Recursively determine which states are required to fetch the target state. + + This will always include potentially dirty substates that depend on vars + in the target_state_cls. Args: - token: The token to get the state for (_substate_key). - state: The state instance to get parent state for. + target_state_cls: The target state class being fetched. + subclasses: Whether to include subclasses of the target state. + required_state_classes: Recursive argument tracking state classes that have already been seen. Returns: - The parent state for the state requested by the token or None if there is no such parent. + The set of state classes required to fetch the target state. """ - parent_state = None - client_token, state_path = _split_substate_key(token) - parent_state_name = state_path.rpartition(".")[0] - if parent_state_name: - cached_substates = None - if state is not None: - cached_substates = [state] - # Retrieve the parent state to populate event handlers onto this substate. - parent_state = await self.get_state( - token=_substate_key(client_token, parent_state_name), - top_level=False, - get_substates=False, - cached_substates=cached_substates, + if required_state_classes is None: + required_state_classes = set() + # Get the substates if requested. + if subclasses: + for substate in target_state_cls.get_substates(): + self._get_required_state_classes( + substate, + subclasses=True, + required_state_classes=required_state_classes, + ) + if target_state_cls in required_state_classes: + return required_state_classes + required_state_classes.add(target_state_cls) + + # Get dependent substates. + for pd_substates in target_state_cls._get_potentially_dirty_states(): + self._get_required_state_classes( + pd_substates, + subclasses=False, + required_state_classes=required_state_classes, ) - return parent_state - async def _populate_substates( + # Get the parent state if it exists. + if parent_state := target_state_cls.get_parent_state(): + self._get_required_state_classes( + parent_state, + subclasses=False, + required_state_classes=required_state_classes, + ) + return required_state_classes + + def _get_populated_states( self, - token: str, - state: BaseState, - all_substates: bool = False, - ): - """Fetch and link substates for the given state instance. - - There is no return value; the side-effect is that `state` will have `substates` populated, - and each substate will have its `parent_state` set to `state`. + target_state: BaseState, + populated_states: dict[str, BaseState] | None = None, + ) -> dict[str, BaseState]: + """Recursively determine which states from target_state are already fetched. Args: - token: The token to get the state for. - state: The state instance to populate substates for. - all_substates: Whether to fetch all substates or just required substates. + target_state: The state to check for populated states. + populated_states: Recursive argument tracking states seen in previous calls. + + Returns: + A dictionary of state full name to state instance. """ - client_token, _ = _split_substate_key(token) - - if all_substates: - # All substates are requested. - fetch_substates = state.get_substates() - else: - # Only _potentially_dirty_substates need to be fetched to recalc computed vars. - fetch_substates = state._potentially_dirty_substates() - - tasks = {} - # Retrieve the necessary substates from redis. - for substate_cls in fetch_substates: - if substate_cls.get_name() in state.substates: - continue - substate_name = substate_cls.get_name() - tasks[substate_name] = asyncio.create_task( - self.get_state( - token=_substate_key(client_token, substate_cls), - top_level=False, - get_substates=all_substates, - parent_state=state, - ) + if populated_states is None: + populated_states = {} + if target_state.get_full_name() in populated_states: + return populated_states + populated_states[target_state.get_full_name()] = target_state + for substate in target_state.substates.values(): + self._get_populated_states(substate, populated_states=populated_states) + if target_state.parent_state is not None: + self._get_populated_states( + target_state.parent_state, populated_states=populated_states ) - - for substate_name, substate_task in tasks.items(): - state.substates[substate_name] = await substate_task + return populated_states @override async def get_state( self, token: str, top_level: bool = True, - get_substates: bool = True, - parent_state: BaseState | None = None, - cached_substates: list[BaseState] | None = None, + for_state_instance: BaseState | None = None, ) -> BaseState: """Get the state for a token. Args: token: The token to get the state for. top_level: If true, return an instance of the top-level state (self.state). - get_substates: If true, also retrieve substates. - parent_state: If provided, use this parent_state instead of getting it from redis. - cached_substates: If provided, attach these substates to the state. + for_state_instance: If provided, attach the requested states to this existing state tree. Returns: The state for the token. Raises: - RuntimeError: when the state_cls is not specified in the token + RuntimeError: when the state_cls is not specified in the token, or when the parent state for a + requested state was not fetched. """ # Split the actual token from the fully qualified substate name. - _, state_path = _split_substate_key(token) + token, state_path = _split_substate_key(token) if state_path: # Get the State class associated with the given path. state_cls = self.state.get_class_substate(state_path) @@ -3414,43 +3325,59 @@ class StateManagerRedis(StateManager): f"StateManagerRedis requires token to be specified in the form of {{token}}_{{state_full_name}}, but got {token}" ) - # The deserialized or newly created (sub)state instance. - state = None + # Determine which states we already have. + flat_state_tree: dict[str, BaseState] = ( + self._get_populated_states(for_state_instance) if for_state_instance else {} + ) - # Fetch the serialized substate from redis. - redis_state = await self.redis.get(token) + # Determine which states from the tree need to be fetched. + required_state_classes = sorted( + self._get_required_state_classes(state_cls, subclasses=True) + - {type(s) for s in flat_state_tree.values()}, + key=lambda x: x.get_full_name(), + ) - if redis_state is not None: - # Deserialize the substate. - with contextlib.suppress(StateSchemaMismatchError): - state = BaseState._deserialize(data=redis_state) - if state is None: - # Key didn't exist or schema mismatch so create a new instance for this token. - state = state_cls( - init_substates=False, - _reflex_internal_init=True, - ) - # Populate parent state if missing and requested. - if parent_state is None: - parent_state = await self._get_parent_state(token, state) - # Set up Bidirectional linkage between this state and its parent. - if parent_state is not None: - parent_state.substates[state.get_name()] = state - state.parent_state = parent_state - # Avoid fetching substates multiple times. - if cached_substates: - for substate in cached_substates: - state.substates[substate.get_name()] = substate - if substate.parent_state is None: - substate.parent_state = state - # Populate substates if requested. - await self._populate_substates(token, state, all_substates=get_substates) + redis_pipeline = self.redis.pipeline() + for state_cls in required_state_classes: + redis_pipeline.get(_substate_key(token, state_cls)) + + for state_cls, redis_state in zip( + required_state_classes, + await redis_pipeline.execute(), + strict=False, + ): + state = None + + if redis_state is not None: + # Deserialize the substate. + with contextlib.suppress(StateSchemaMismatchError): + state = BaseState._deserialize(data=redis_state) + if state is None: + # Key didn't exist or schema mismatch so create a new instance for this token. + state = state_cls( + init_substates=False, + _reflex_internal_init=True, + ) + flat_state_tree[state.get_full_name()] = state + if state.get_parent_state() is not None: + parent_state_name, _dot, state_name = state.get_full_name().rpartition( + "." + ) + parent_state = flat_state_tree.get(parent_state_name) + if parent_state is None: + raise RuntimeError( + f"Parent state for {state.get_full_name()} was not found " + "in the state tree, but should have already been fetched. " + "This is a bug", + ) + parent_state.substates[state_name] = state + state.parent_state = parent_state # To retain compatibility with previous implementation, by default, we return - # the top-level state by chasing `parent_state` pointers up the tree. + # the top-level state which should always be fetched or already cached. if top_level: - return state._get_root_state() - return state + return flat_state_tree[self.state.get_full_name()] + return flat_state_tree[state_cls.get_full_name()] @override async def set_state( @@ -3541,7 +3468,9 @@ class StateManagerRedis(StateManager): @validator("lock_warning_threshold") @classmethod - def validate_lock_warning_threshold(cls, lock_warning_threshold: int, values): + def validate_lock_warning_threshold( + cls, lock_warning_threshold: int, values: dict[str, int] + ): """Validate the lock warning threshold. Args: @@ -3702,8 +3631,7 @@ def get_state_manager() -> StateManager: Returns: The state manager. """ - app = getattr(prerequisites.get_app(), constants.CompileVars.APP) - return app.state_manager + return prerequisites.get_and_validate_app().app.state_manager class MutableProxy(wrapt.ObjectProxy): @@ -3778,9 +3706,9 @@ class MutableProxy(wrapt.ObjectProxy): 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] ), }, ) @@ -3810,10 +3738,10 @@ class MutableProxy(wrapt.ObjectProxy): def _mark_dirty( self, - wrapped=None, - instance=None, - args=(), - kwargs=None, + wrapped: Callable | None = None, + instance: BaseState | None = None, + args: tuple = (), + kwargs: dict | None = None, ) -> Any: """Mark the state as dirty, then call a wrapped function. @@ -3887,7 +3815,9 @@ class MutableProxy(wrapt.ObjectProxy): ) return value - def _wrap_recursive_decorator(self, wrapped, instance, args, kwargs) -> Any: + def _wrap_recursive_decorator( + self, wrapped: Callable, instance: BaseState, args: list, kwargs: dict + ) -> Any: """Wrap a function that returns a possibly mutable value. Intended for use with `FunctionWrapper` from the `wrapt` library. @@ -3933,7 +3863,7 @@ class MutableProxy(wrapt.ObjectProxy): ): # 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, ) @@ -3946,7 +3876,7 @@ class MutableProxy(wrapt.ObjectProxy): return value - def __getitem__(self, key) -> Any: + def __getitem__(self, key: Any) -> Any: """Get the item on the proxied object and return a proxy if mutable. Args: @@ -3969,7 +3899,7 @@ class MutableProxy(wrapt.ObjectProxy): # Recursively wrap mutable items retrieved through this proxy. yield self._wrap_recursive(value) - def __delattr__(self, name): + def __delattr__(self, name: str): """Delete the attribute on the proxied object and mark state dirty. Args: @@ -3977,7 +3907,7 @@ class MutableProxy(wrapt.ObjectProxy): """ self._mark_dirty(super().__delattr__, args=(name,)) - def __delitem__(self, key): + def __delitem__(self, key: str): """Delete the item on the proxied object and mark state dirty. Args: @@ -3985,7 +3915,7 @@ class MutableProxy(wrapt.ObjectProxy): """ self._mark_dirty(super().__delitem__, args=(key,)) - def __setitem__(self, key, value): + def __setitem__(self, key: str, value: Any): """Set the item on the proxied object and mark state dirty. Args: @@ -3994,7 +3924,7 @@ class MutableProxy(wrapt.ObjectProxy): """ self._mark_dirty(super().__setitem__, args=(key, value)) - def __setattr__(self, name, value): + def __setattr__(self, name: str, value: Any): """Set the attribute on the proxied object and mark state dirty. If the attribute starts with "_self_", then the state is NOT marked @@ -4018,7 +3948,7 @@ class MutableProxy(wrapt.ObjectProxy): """ return copy.copy(self.__wrapped__) - def __deepcopy__(self, memo=None) -> Any: + def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Any: """Return a deepcopy of the proxy. Args: @@ -4029,7 +3959,7 @@ class MutableProxy(wrapt.ObjectProxy): """ return copy.deepcopy(self.__wrapped__, memo=memo) - def __reduce_ex__(self, protocol_version): + def __reduce_ex__(self, protocol_version: SupportsIndex): """Get the state for redis serialization. This method is called by cloudpickle to serialize the object. @@ -4058,10 +3988,10 @@ def serialize_mutable_proxy(mp: MutableProxy): return mp.__wrapped__ -_orig_json_JSONEncoder_default = json.JSONEncoder.default +_orig_json_encoder_default = json.JSONEncoder.default -def _json_JSONEncoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any: +def _json_encoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any: """Wrap JSONEncoder.default to handle MutableProxy objects. Args: @@ -4075,10 +4005,10 @@ def _json_JSONEncoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any: return o.__wrapped__ except AttributeError: pass - return _orig_json_JSONEncoder_default(self, o) + return _orig_json_encoder_default(self, o) -json.JSONEncoder.default = _json_JSONEncoder_default_wrapper +json.JSONEncoder.default = _json_encoder_default_wrapper class ImmutableMutableProxy(MutableProxy): @@ -4093,10 +4023,10 @@ class ImmutableMutableProxy(MutableProxy): def _mark_dirty( self, - wrapped=None, - instance=None, - args=(), - kwargs=None, + wrapped: Callable | None = None, + instance: BaseState | None = None, + args: tuple = (), + kwargs: dict | None = None, ) -> Any: """Raise an exception when an attempt is made to modify the object. @@ -4147,12 +4077,19 @@ def reload_state_module( state: Recursive argument for the state class to reload. """ + # Clean out all potentially dirty states of reloaded modules. + for pd_state in tuple(state._potentially_dirty_states): + with contextlib.suppress(ValueError): + if ( + state.get_root_state().get_class_substate(pd_state).__module__ == module + and module is not None + ): + state._potentially_dirty_states.remove(pd_state) for subclass in tuple(state.class_subclasses): reload_state_module(module=module, state=subclass) if subclass.__module__ == module and module is not None: state.class_subclasses.remove(subclass) state._always_dirty_substates.discard(subclass.get_name()) - state._computed_var_dependencies = defaultdict(set) - state._substate_var_dependencies = defaultdict(set) + state._var_dependencies = {} state._init_var_dependency_dicts() state.get_class_substate.cache_clear() diff --git a/reflex/style.py b/reflex/style.py index a205cdc4a..192835ca3 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") @@ -182,7 +182,9 @@ def convert( var_data = None # Track import/hook data from any Vars in the style dict. out = {} - def update_out_dict(return_value, keys_to_update): + def update_out_dict( + return_value: Var | dict | list | str, keys_to_update: tuple[str, ...] + ): for k in keys_to_update: out[k] = return_value @@ -287,9 +289,31 @@ class Style(dict): _var = LiteralVar.create(value) if _var is not None: # Carry the imports/hooks when setting a Var as a value. - self._var_data = VarData.merge(self._var_data, _var._get_all_var_data()) + self._var_data = VarData.merge( + getattr(self, "_var_data", None), _var._get_all_var_data() + ) super().__setitem__(key, value) + def __or__(self, other: Style | dict) -> Style: + """Combine two styles. + + Args: + other: The other style to combine. + + Returns: + The combined style. + """ + other_var_data = None + if not isinstance(other, Style): + other_dict, other_var_data = convert(other) + else: + other_dict, other_var_data = other, other._var_data + + new_style = Style(super().__or__(other_dict)) + if self._var_data or other_var_data: + new_style._var_data = VarData.merge(self._var_data, other_var_data) + return new_style + def _format_emotion_style_pseudo_selector(key: str) -> str: """Format a pseudo selector for emotion CSS-in-JS. diff --git a/reflex/testing.py b/reflex/testing.py index b3dedf398..25f9e7aac 100644 --- a/reflex/testing.py +++ b/reflex/testing.py @@ -80,17 +80,17 @@ T = TypeVar("T") 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 # borrowed from py3.11 -class chdir(contextlib.AbstractContextManager): +class chdir(contextlib.AbstractContextManager): # noqa: N801 """Non thread-safe context manager to change the current working directory.""" - def __init__(self, path): + def __init__(self, path: str | Path): """Prepare contextmanager. Args: @@ -258,7 +258,7 @@ class AppHarness: 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( [ @@ -282,6 +282,7 @@ class AppHarness: before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy() # Ensure the AppHarness test does not skip State assignment due to running via pytest os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None) + os.environ[reflex.constants.APP_HARNESS_FLAG] = "true" self.app_module = reflex.utils.prerequisites.get_compiled_app( # Do not reload the module for pre-existing apps (only apps generated from source) reload=self.app_source is not None @@ -293,11 +294,15 @@ class AppHarness: 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.""" @@ -322,8 +327,8 @@ class AppHarness: return _shutdown_redis - def _start_backend(self, port=0): - if self.app_instance is None: + def _start_backend(self, port: int = 0): + if self.app_instance is None or self.app_instance.api is None: raise RuntimeError("App was not initialized.") self.backend = uvicorn.Server( uvicorn.Config( @@ -352,12 +357,12 @@ class AppHarness: self.app_instance.state_manager, StateManagerRedis, ) - and self.app_instance.state is not None + and self.app_instance._state is not None ): with contextlib.suppress(RuntimeError): await self.app_instance.state_manager.close() self.app_instance._state_manager = StateManagerRedis.create( - state=self.app_instance.state, + state=self.app_instance._state, ) if not isinstance(self.app_instance.state_manager, StateManagerRedis): raise RuntimeError("Failed to reset state manager.") @@ -425,7 +430,7 @@ class AppHarness: return self @staticmethod - def get_app_global_source(key, value): + def get_app_global_source(key: str, value: Any): """Get the source code of a global object. If value is a function or class we render the actual source of value otherwise we assign value to key. @@ -620,23 +625,23 @@ class AppHarness: 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: @@ -652,7 +657,7 @@ class AppHarness: 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 @@ -884,8 +889,8 @@ class Subdir404TCPServer(socketserver.TCPServer): 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] ) @@ -932,6 +937,7 @@ class AppHarnessProd(AppHarness): frontend=True, backend=False, loglevel=reflex.constants.LogLevel.INFO, + env=reflex.constants.Env.PROD, ) self.frontend_thread = threading.Thread(target=self._run_frontend) diff --git a/reflex/utils/build.py b/reflex/utils/build.py index e263374e1..9e35ab984 100644 --- a/reflex/utils/build.py +++ b/reflex/utils/build.py @@ -13,17 +13,21 @@ from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn from reflex import constants from reflex.config import get_config from reflex.utils import console, path_ops, prerequisites, processes +from reflex.utils.exec import is_in_app_harness def set_env_json(): """Write the upload url to a REFLEX_JSON.""" path_ops.update_json_file( str(prerequisites.get_web_dir() / constants.Dirs.ENV_JSON), - {endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint}, + { + **{endpoint.name: endpoint.get_url() for endpoint in constants.Endpoint}, + "TEST_MODE": is_in_app_harness(), + }, ) -def generate_sitemap_config(deploy_url: str, export=False): +def generate_sitemap_config(deploy_url: str, export: bool = False): """Generate the sitemap config file. Args: diff --git a/reflex/utils/codespaces.py b/reflex/utils/codespaces.py index 7ff686129..bb5286e31 100644 --- a/reflex/utils/codespaces.py +++ b/reflex/utils/codespaces.py @@ -42,10 +42,7 @@ def codespaces_port_forwarding_domain() -> str | None: Returns: The domain for port forwarding in Github Codespaces, or None if not running in Codespaces. """ - GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN = os.getenv( - "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN" - ) - return GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN + return os.getenv("GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN") def is_running_in_codespaces() -> bool: diff --git a/reflex/utils/compat.py b/reflex/utils/compat.py index e63492a6b..e4fb5eb35 100644 --- a/reflex/utils/compat.py +++ b/reflex/utils/compat.py @@ -2,6 +2,7 @@ import contextlib import sys +from typing import Any async def windows_hot_reload_lifespan_hack(): @@ -50,11 +51,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): @@ -74,7 +75,7 @@ with pydantic_v1_patch(): import sqlmodel as sqlmodel -def sqlmodel_field_has_primary_key(field) -> bool: +def sqlmodel_field_has_primary_key(field: Any) -> bool: """Determines if a field is a priamary. Args: diff --git a/reflex/utils/console.py b/reflex/utils/console.py index 8929b63b6..d5b7a0d6e 100644 --- a/reflex/utils/console.py +++ b/reflex/utils/console.py @@ -51,20 +51,12 @@ def set_log_level(log_level: LogLevel): log_level: The log level to set. Raises: - ValueError: If the log level is invalid. + TypeError: If the log level is a string. """ if not isinstance(log_level, LogLevel): - deprecate( - feature_name="Passing a string to set_log_level", - reason="use reflex.constants.LogLevel enum instead", - deprecation_version="0.6.6", - removal_version="0.7.0", + raise TypeError( + f"log_level must be a LogLevel enum value, got {log_level} of type {type(log_level)} instead." ) - try: - log_level = getattr(LogLevel, log_level.upper()) - except AttributeError as ae: - raise ValueError(f"Invalid log level: {log_level}") from ae - global _LOG_LEVEL _LOG_LEVEL = log_level @@ -204,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 ] @@ -283,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. @@ -298,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/exceptions.py b/reflex/utils/exceptions.py index 339abcda1..05fbb297c 100644 --- a/reflex/utils/exceptions.py +++ b/reflex/utils/exceptions.py @@ -1,6 +1,6 @@ """Custom Exceptions.""" -from typing import NoReturn +from typing import Any class ReflexError(Exception): @@ -11,7 +11,7 @@ class ConfigError(ReflexError): """Custom exception for config related errors.""" -class InvalidStateManagerMode(ReflexError, ValueError): +class InvalidStateManagerModeError(ReflexError, ValueError): """Raised when an invalid state manager mode is provided.""" @@ -31,6 +31,22 @@ class ComponentTypeError(ReflexError, TypeError): """Custom TypeError for component related errors.""" +class ChildrenTypeError(ComponentTypeError): + """Raised when the children prop of a component is not a valid type.""" + + def __init__(self, component: str, child: Any): + """Initialize the exception. + + Args: + component: The name of the component. + child: The child that caused the error. + """ + super().__init__( + f"Component {component} received child {child} of type {type(child)}. " + "Accepted types are other components, state vars, or primitive Python types (dict excluded)." + ) + + class EventHandlerTypeError(ReflexError, TypeError): """Custom TypeError for event handler related errors.""" @@ -59,6 +75,34 @@ class VarAttributeError(ReflexError, AttributeError): """Custom AttributeError for var related errors.""" +class UntypedVarError(ReflexError, TypeError): + """Custom TypeError for untyped var errors.""" + + +class UntypedComputedVarError(ReflexError, TypeError): + """Custom TypeError for untyped computed var errors.""" + + def __init__(self, var_name: str): + """Initialize the UntypedComputedVarError. + + Args: + var_name: The name of the computed var. + """ + super().__init__(f"Computed var '{var_name}' must have a type annotation.") + + +class MissingAnnotationError(ReflexError, TypeError): + """Custom TypeError for missing annotations.""" + + def __init__(self, var_name: str): + """Initialize the MissingAnnotationError. + + Args: + var_name: The name of the var. + """ + super().__init__(f"Var '{var_name}' must have a type annotation.") + + class UploadValueError(ReflexError, ValueError): """Custom ValueError for upload related errors.""" @@ -95,43 +139,43 @@ class MatchTypeError(ReflexError, TypeError): """Raised when the return types of match cases are different.""" -class EventHandlerArgTypeMismatch(ReflexError, TypeError): +class EventHandlerArgTypeMismatchError(ReflexError, TypeError): """Raised when the annotations of args accepted by an EventHandler differs from the spec of the event trigger.""" -class EventFnArgMismatch(ReflexError, TypeError): +class EventFnArgMismatchError(ReflexError, TypeError): """Raised when the number of args required by an event handler is more than provided by the event trigger.""" -class DynamicRouteArgShadowsStateVar(ReflexError, NameError): +class DynamicRouteArgShadowsStateVarError(ReflexError, NameError): """Raised when a dynamic route arg shadows a state var.""" -class ComputedVarShadowsStateVar(ReflexError, NameError): +class ComputedVarShadowsStateVarError(ReflexError, NameError): """Raised when a computed var shadows a state var.""" -class ComputedVarShadowsBaseVars(ReflexError, NameError): +class ComputedVarShadowsBaseVarsError(ReflexError, NameError): """Raised when a computed var shadows a base var.""" -class EventHandlerShadowsBuiltInStateMethod(ReflexError, NameError): +class EventHandlerShadowsBuiltInStateMethodError(ReflexError, NameError): """Raised when an event handler shadows a built-in state method.""" -class GeneratedCodeHasNoFunctionDefs(ReflexError): +class GeneratedCodeHasNoFunctionDefsError(ReflexError): """Raised when refactored code generated with flexgen has no functions defined.""" -class PrimitiveUnserializableToJSON(ReflexError, ValueError): +class PrimitiveUnserializableToJSONError(ReflexError, ValueError): """Raised when a primitive type is unserializable to JSON. Usually with NaN and Infinity.""" -class InvalidLifespanTaskType(ReflexError, TypeError): +class InvalidLifespanTaskTypeError(ReflexError, TypeError): """Raised when an invalid task type is registered as a lifespan task.""" -class DynamicComponentMissingLibrary(ReflexError, ValueError): +class DynamicComponentMissingLibraryError(ReflexError, ValueError): """Raised when a dynamic component is missing a library.""" @@ -147,7 +191,7 @@ class EnvironmentVarValueError(ReflexError, ValueError): """Raised when an environment variable is set to an invalid value.""" -class DynamicComponentInvalidSignature(ReflexError, TypeError): +class DynamicComponentInvalidSignatureError(ReflexError, TypeError): """Raised when a dynamic component has an invalid signature.""" @@ -170,23 +214,25 @@ class StateMismatchError(ReflexError, ValueError): class SystemPackageMissingError(ReflexError): """Raised when a system package is missing.""" + def __init__(self, package: str): + """Initialize the SystemPackageMissingError. -def raise_system_package_missing_error(package: str) -> NoReturn: - """Raise a SystemPackageMissingError. + Args: + package: The missing package. + """ + from reflex.constants import IS_MACOS - Args: - package: The name of the missing system package. + extra = ( + f" You can do so by running 'brew install {package}'." if IS_MACOS else "" + ) + super().__init__( + f"System package '{package}' is missing." + f" Please install it through your system package manager.{extra}" + ) - Raises: - SystemPackageMissingError: The raised exception. - """ - from reflex.constants import IS_MACOS - raise SystemPackageMissingError( - f"System package '{package}' is missing." - " Please install it through your system package manager." - + (f" You can do so by running 'brew install {package}'." if IS_MACOS else "") - ) +class EventDeserializationError(ReflexError, ValueError): + """Raised when an event cannot be deserialized.""" class InvalidLockWarningThresholdError(ReflexError): diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index 621c4a608..67df7ea91 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -71,7 +71,9 @@ 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: bool = True +): """Run the process and launch the URL. Args: @@ -89,7 +91,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(), @@ -134,7 +136,7 @@ def run_process_and_launch_url(run_command: list[str], backend_present=True): break # while True -def run_frontend(root: Path, port: str, backend_present=True): +def run_frontend(root: Path, port: str, backend_present: bool = True): """Run the frontend. Args: @@ -151,12 +153,12 @@ 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, ) -def run_frontend_prod(root: Path, port: str, backend_present=True): +def run_frontend_prod(root: Path, port: str, backend_present: bool = True): """Run the frontend. Args: @@ -173,7 +175,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, ) @@ -240,7 +242,32 @@ def run_backend( run_uvicorn_backend(host, port, loglevel) -def run_uvicorn_backend(host, port, loglevel: LogLevel): +def get_reload_dirs() -> list[Path]: + """Get the reload directories for the backend. + + Returns: + The reload directories for the backend. + """ + config = get_config() + reload_dirs = [Path(config.app_name)] + if config.app_module is not None and config.app_module.__file__: + module_path = Path(config.app_module.__file__).resolve().parent + + while module_path.parent.name: + if any( + sibling_file.name == "__init__.py" + for sibling_file in module_path.parent.iterdir() + ): + # go up a level to find dir without `__init__.py` + module_path = module_path.parent + else: + break + + reload_dirs = [module_path] + return reload_dirs + + +def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel): """Run the backend in development mode using Uvicorn. Args: @@ -256,11 +283,11 @@ def run_uvicorn_backend(host, port, loglevel: LogLevel): port=port, log_level=loglevel.value, reload=True, - reload_dirs=[get_config().app_name], + reload_dirs=list(map(str, get_reload_dirs())), ) -def run_granian_backend(host, port, loglevel: LogLevel): +def run_granian_backend(host: str, port: int, loglevel: LogLevel): """Run the backend in development mode using Granian. Args: @@ -270,9 +297,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(), @@ -281,8 +310,8 @@ def run_granian_backend(host, port, loglevel: LogLevel): interface=Interfaces.ASGI, log_level=LogLevels(loglevel.value), reload=True, - reload_paths=[Path(get_config().app_name)], - reload_ignore_dirs=[".web"], + reload_paths=get_reload_dirs(), + reload_ignore_dirs=[".web", ".states"], ).serve() except ImportError: console.error( @@ -325,7 +354,7 @@ def run_backend_prod( run_uvicorn_backend_prod(host, port, loglevel) -def run_uvicorn_backend_prod(host, port, loglevel): +def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel): """Run the backend in production mode using Uvicorn. Args: @@ -339,11 +368,11 @@ def run_uvicorn_backend_prod(host, port, loglevel): app_module = get_app_module() - RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --max-requests {config.gunicorn_max_requests} --max-requests-jitter {config.gunicorn_max_requests_jitter} --preload --timeout {config.timeout} --log-level critical".split() - RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split() + run_backend_prod = f"gunicorn --worker-class {config.gunicorn_worker_class} --max-requests {config.gunicorn_max_requests} --max-requests-jitter {config.gunicorn_max_requests_jitter} --preload --timeout {config.timeout} --log-level critical".split() + run_backend_prod_windows = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split() command = ( [ - *RUN_BACKEND_PROD_WINDOWS, + *run_backend_prod_windows, "--host", host, "--port", @@ -352,7 +381,7 @@ def run_uvicorn_backend_prod(host, port, loglevel): ] if constants.IS_WINDOWS else [ - *RUN_BACKEND_PROD, + *run_backend_prod, "--bind", f"{host}:{port}", "--threads", @@ -377,7 +406,7 @@ def run_uvicorn_backend_prod(host, port, loglevel): ) -def run_granian_backend_prod(host, port, loglevel): +def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel): """Run the backend in production mode using Granian. Args: @@ -388,7 +417,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", @@ -442,22 +473,22 @@ def output_system_info(): system = platform.system() + fnm_info = f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]" + if system != "Windows" or ( system == "Windows" and prerequisites.is_windows_bun_supported() ): dependencies.extend( [ - f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]", - f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]", + fnm_info, + f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {path_ops.get_bun_path()})]", ], ) else: - dependencies.append( - f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]", - ) + dependencies.append(fnm_info) if system == "Linux": - import distro # type: ignore + import distro # pyright: ignore[reportMissingImports] os_version = distro.name(pretty=True) else: @@ -469,11 +500,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')}") @@ -487,6 +518,15 @@ def is_testing_env() -> bool: return constants.PYTEST_CURRENT_TEST in os.environ +def is_in_app_harness() -> bool: + """Whether the app is running in the app harness. + + Returns: + True if the app is running in the app harness. + """ + return constants.APP_HARNESS_FLAG in os.environ + + def is_prod_mode() -> bool: """Check if the app is running in production mode. @@ -495,48 +535,3 @@ def is_prod_mode() -> bool: """ current_mode = environment.REFLEX_ENV_MODE.get() return current_mode == constants.Env.PROD - - -def is_frontend_only() -> bool: - """Check if the app is running in frontend-only mode. - - Returns: - True if the app is running in frontend-only mode. - """ - console.deprecate( - "is_frontend_only() is deprecated and will be removed in a future release.", - reason="Use `environment.REFLEX_FRONTEND_ONLY.get()` instead.", - deprecation_version="0.6.5", - removal_version="0.7.0", - ) - return environment.REFLEX_FRONTEND_ONLY.get() - - -def is_backend_only() -> bool: - """Check if the app is running in backend-only mode. - - Returns: - True if the app is running in backend-only mode. - """ - console.deprecate( - "is_backend_only() is deprecated and will be removed in a future release.", - reason="Use `environment.REFLEX_BACKEND_ONLY.get()` instead.", - deprecation_version="0.6.5", - removal_version="0.7.0", - ) - return environment.REFLEX_BACKEND_ONLY.get() - - -def should_skip_compile() -> bool: - """Whether the app should skip compile. - - Returns: - True if the app should skip compile. - """ - console.deprecate( - "should_skip_compile() is deprecated and will be removed in a future release.", - reason="Use `environment.REFLEX_SKIP_COMPILE.get()` instead.", - deprecation_version="0.6.5", - removal_version="0.7.0", - ) - return environment.REFLEX_SKIP_COMPILE.get() diff --git a/reflex/utils/export.py b/reflex/utils/export.py index 2fbf633f6..edb4a6e1a 100644 --- a/reflex/utils/export.py +++ b/reflex/utils/export.py @@ -4,7 +4,7 @@ from pathlib import Path from typing import Optional from reflex import constants -from reflex.config import get_config +from reflex.config import environment, get_config from reflex.utils import build, console, exec, prerequisites, telemetry config = get_config() @@ -18,6 +18,7 @@ def export( upload_db_file: bool = False, api_url: Optional[str] = None, deploy_url: Optional[str] = None, + env: constants.Env = constants.Env.PROD, loglevel: constants.LogLevel = console._LOG_LEVEL, ): """Export the app to a zip file. @@ -30,11 +31,15 @@ def export( upload_db_file: Whether to upload the database file. Defaults to False. api_url: The API URL to use. Defaults to None. deploy_url: The deploy URL to use. Defaults to None. + env: The environment to use. Defaults to constants.Env.PROD. loglevel: The log level to use. Defaults to console._LOG_LEVEL. """ # Set the log level. console.set_log_level(loglevel) + # Set env mode in the environment + environment.REFLEX_ENV_MODE.set(env) + # Override the config url values if provided. if api_url is not None: config.api_url = str(api_url) diff --git a/reflex/utils/format.py b/reflex/utils/format.py index 1d6671a0b..6f05e0982 100644 --- a/reflex/utils/format.py +++ b/reflex/utils/format.py @@ -11,7 +11,6 @@ from typing import TYPE_CHECKING, Any, List, Optional, Union from reflex import constants from reflex.constants.state import FRONTEND_EVENT_STATE from reflex.utils import exceptions -from reflex.utils.console import deprecate if TYPE_CHECKING: from reflex.components.component import ComponentStyle @@ -221,7 +220,7 @@ def _escape_js_string(string: str) -> str: """ # TODO: we may need to re-vist this logic after new Var API is implemented. - def escape_outside_segments(segment): + def escape_outside_segments(segment: str): """Escape backticks in segments outside of `${}`. Args: @@ -284,7 +283,7 @@ def format_var(var: Var) -> str: return str(var) -def format_route(route: str, format_case=True) -> str: +def format_route(route: str, format_case: bool = True) -> str: """Format the given route. Args: @@ -378,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. @@ -502,37 +501,6 @@ if TYPE_CHECKING: from reflex.vars import Var -def format_event_chain( - event_chain: EventChain | Var[EventChain], - event_arg: Var | None = None, -) -> str: - """DEPRECATED: format an event chain as a javascript invocation. - - Use str(rx.Var.create(event_chain)) instead. - - Args: - event_chain: The event chain to format. - event_arg: this argument is ignored. - - Returns: - Compiled javascript code to queue the given event chain on the frontend. - """ - deprecate( - feature_name="format_event_chain", - reason="Use str(rx.Var.create(event_chain)) instead", - deprecation_version="0.6.0", - removal_version="0.7.0", - ) - - from reflex.vars import Var - from reflex.vars.function import ArgsFunctionOperation - - result = Var.create(event_chain) - if isinstance(result, ArgsFunctionOperation): - result = result._return_expr - return str(result) - - def format_queue_events( events: EventType | None = None, args_spec: Optional[ArgsSpec] = None, @@ -565,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})" @@ -589,7 +557,7 @@ def format_queue_events( 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." @@ -601,7 +569,7 @@ def format_queue_events( 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 bd422ecc0..46e8e7362 100644 --- a/reflex/utils/imports.py +++ b/reflex/utils/imports.py @@ -90,7 +90,7 @@ def collapse_imports( } -@dataclasses.dataclass(order=True, frozen=True) +@dataclasses.dataclass(frozen=True) class ImportVar: """An import var.""" @@ -122,7 +122,7 @@ class ImportVar: """ 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/lazy_loader.py b/reflex/utils/lazy_loader.py index 61e3967e5..eba89532d 100644 --- a/reflex/utils/lazy_loader.py +++ b/reflex/utils/lazy_loader.py @@ -1,11 +1,17 @@ """Module to implement lazy loading in reflex.""" +from __future__ import annotations + import copy import lazy_loader as lazy -def attach(package_name, submodules=None, submod_attrs=None): +def attach( + package_name: str, + submodules: set | None = None, + submod_attrs: dict | None = None, +): """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach. The lazy loader __getattr__ doesn't support tuples as list values. We needed to add this functionality (tuples) in Reflex to support 'import as _' statements. This function diff --git a/reflex/utils/path_ops.py b/reflex/utils/path_ops.py index 38560977e..edab085ff 100644 --- a/reflex/utils/path_ops.py +++ b/reflex/utils/path_ops.py @@ -9,7 +9,7 @@ import shutil from pathlib import Path from reflex import constants -from reflex.config import environment +from reflex.config import environment, get_config # Shorthand for join. join = os.linesep.join @@ -118,7 +118,7 @@ def ln(src: str | Path, dest: str | Path, overwrite: bool = False) -> bool: return True -def which(program: str | Path) -> str | Path | None: +def which(program: str | Path) -> Path | None: """Find the path to an executable. Args: @@ -127,7 +127,8 @@ def which(program: str | Path) -> str | Path | None: Returns: The path to the executable. """ - return shutil.which(str(program)) + which_result = shutil.which(program) + return Path(which_result) if which_result else None def use_system_node() -> bool: @@ -156,12 +157,12 @@ def get_node_bin_path() -> Path | None: """ bin_path = Path(constants.Node.BIN_PATH) if not bin_path.exists(): - str_path = which("node") - return Path(str_path).parent.resolve() if str_path else None - return bin_path.resolve() + path = which("node") + return path.parent.absolute() if path else None + return bin_path.absolute() -def get_node_path() -> str | None: +def get_node_path() -> Path | None: """Get the node binary path. Returns: @@ -169,12 +170,11 @@ def get_node_path() -> str | None: """ node_path = Path(constants.Node.PATH) if use_system_node() or not node_path.exists(): - system_node_path = which("node") - return str(system_node_path) if system_node_path else None - return str(node_path) + node_path = which("node") + return node_path -def get_npm_path() -> str | None: +def get_npm_path() -> Path | None: """Get npm binary path. Returns: @@ -182,9 +182,20 @@ def get_npm_path() -> str | None: """ npm_path = Path(constants.Node.NPM_PATH) if use_system_node() or not npm_path.exists(): - system_npm_path = which("npm") - return str(system_npm_path) if system_npm_path else None - return str(npm_path) + npm_path = which("npm") + return npm_path.absolute() if npm_path else None + + +def get_bun_path() -> Path | None: + """Get bun binary path. + + Returns: + The path to the bun binary file. + """ + bun_path = get_config().bun_path + if use_system_bun() or not bun_path.exists(): + bun_path = which("bun") + return bun_path.absolute() if bun_path else None def update_json_file(file_path: str | Path, update_dict: dict[str, int | str]): @@ -196,6 +207,9 @@ def update_json_file(file_path: str | Path, update_dict: dict[str, int | str]): """ fp = Path(file_path) + # Create the parent directory if it doesn't exist. + fp.parent.mkdir(parents=True, exist_ok=True) + # Create the file if it doesn't exist. fp.touch(exist_ok=True) diff --git a/reflex/utils/prerequisites.py b/reflex/utils/prerequisites.py index e450393c3..4741400f8 100644 --- a/reflex/utils/prerequisites.py +++ b/reflex/utils/prerequisites.py @@ -7,6 +7,7 @@ import dataclasses import functools import importlib import importlib.metadata +import importlib.util import json import os import platform @@ -17,11 +18,12 @@ import stat import sys import tempfile import time +import typing import zipfile from datetime import datetime from pathlib import Path from types import ModuleType -from typing import Callable, List, Optional +from typing import Callable, List, NamedTuple, Optional import httpx import typer @@ -36,15 +38,25 @@ from reflex.compiler import templates from reflex.config import Config, environment, get_config from reflex.utils import console, net, path_ops, processes, redir from reflex.utils.exceptions import ( - GeneratedCodeHasNoFunctionDefs, - raise_system_package_missing_error, + GeneratedCodeHasNoFunctionDefsError, + SystemPackageMissingError, ) from reflex.utils.format import format_library_name from reflex.utils.registry import _get_npm_registry +if typing.TYPE_CHECKING: + from reflex.app import App + CURRENTLY_INSTALLING_NODE = False +class AppInfo(NamedTuple): + """A tuple containing the app instance and module.""" + + app: App + module: ModuleType + + @dataclasses.dataclass(frozen=True) class Template: """A template for a Reflex app.""" @@ -75,16 +87,15 @@ def get_web_dir() -> Path: return environment.REFLEX_WEB_WORKDIR.get() -def _python_version_check(): - """Emit deprecation warning for deprecated python versions.""" - # Check for end-of-life python versions. - if sys.version_info < (3, 10): - console.deprecate( - feature_name="Support for Python 3.9 and older", - reason="please upgrade to Python 3.10 or newer", - deprecation_version="0.6.0", - removal_version="0.7.0", - ) +def get_states_dir() -> Path: + """Get the working directory for the states. + + Can be overridden with REFLEX_STATES_WORKDIR. + + Returns: + The working directory. + """ + return environment.REFLEX_STATES_WORKDIR.get() def check_latest_package_version(package_name: str): @@ -109,8 +120,6 @@ def check_latest_package_version(package_name: str): console.warn( f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'" ) - # Check for deprecated python versions - _python_version_check() except Exception: pass @@ -167,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 @@ -180,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: @@ -196,10 +205,13 @@ def get_bun_version() -> version.Version | None: Returns: The version of bun. """ + bun_path = path_ops.get_bun_path() + if bun_path is None: + return None try: # Run the bun -v command and capture the output - result = processes.new_process([str(get_config().bun_path), "-v"], run=True) - return version.parse(result.stdout) # type: ignore + result = processes.new_process([str(bun_path), "-v"], run=True) + return version.parse(str(result.stdout)) # pyright: ignore [reportArgumentType] except FileNotFoundError: return None except version.InvalidVersion as e: @@ -243,7 +255,7 @@ def get_package_manager(on_failure_return_none: bool = False) -> str | None: """ npm_path = path_ops.get_npm_path() if npm_path is not None: - return str(Path(npm_path).resolve()) + return str(npm_path) if on_failure_return_none: return None raise FileNotFoundError("NPM not found. You may need to run `reflex init`.") @@ -267,6 +279,22 @@ def windows_npm_escape_hatch() -> bool: return environment.REFLEX_USE_NPM.get() +def _check_app_name(config: Config): + """Check if the app name is set in the config. + + Args: + config: The config object. + + Raises: + RuntimeError: If the app name is not set in the config. + """ + if not config.app_name: + raise RuntimeError( + "Cannot get the app module because `app_name` is not set in rxconfig! " + "If this error occurs in a reflex test case, ensure that `get_app` is mocked." + ) + + def get_app(reload: bool = False) -> ModuleType: """Get the app module based on the default config. @@ -277,22 +305,23 @@ def get_app(reload: bool = False) -> ModuleType: The app based on the default config. Raises: - RuntimeError: If the app name is not set in the config. + Exception: If an error occurs while getting the app module. """ from reflex.utils import telemetry try: environment.RELOAD_CONFIG.set(reload) config = get_config() - if not config.app_name: - raise RuntimeError( - "Cannot get the app module because `app_name` is not set in rxconfig! " - "If this error occurs in a reflex test case, ensure that `get_app` is mocked." - ) + + _check_app_name(config) + module = config.module sys.path.insert(0, str(Path.cwd())) - app = __import__(module, fromlist=(constants.CompileVars.APP,)) - + app = ( + __import__(module, fromlist=(constants.CompileVars.APP,)) + if not config.app_module + else config.app_module + ) if reload: from reflex.state import reload_state_module @@ -301,11 +330,34 @@ def get_app(reload: bool = False) -> ModuleType: # Reload the app module. importlib.reload(app) - - return app except Exception as ex: telemetry.send_error(ex, context="frontend") raise + else: + return app + + +def get_and_validate_app(reload: bool = False) -> AppInfo: + """Get the app instance based on the default config and validate it. + + Args: + reload: Re-import the app module from disk + + Returns: + The app instance and the app module. + + Raises: + RuntimeError: If the app instance is not an instance of rx.App. + """ + from reflex.app import App + + app_module = get_app(reload=reload) + app = getattr(app_module, constants.CompileVars.APP) + if not isinstance(app, App): + raise RuntimeError( + "The app instance in the specified app_module_import in rxconfig must be an instance of rx.App." + ) + return AppInfo(app=app, module=app_module) def get_compiled_app(reload: bool = False, export: bool = False) -> ModuleType: @@ -318,8 +370,7 @@ def get_compiled_app(reload: bool = False, export: bool = False) -> ModuleType: Returns: The compiled app based on the default config. """ - app_module = get_app(reload=reload) - app = getattr(app_module, constants.CompileVars.APP) + app, app_module = get_and_validate_app(reload=reload) # For py3.9 compatibility when redis is used, we MUST add any decorator pages # before compiling the app in a thread to avoid event loop error (REF-2172). app._apply_decorated_pages() @@ -427,6 +478,167 @@ def validate_app_name(app_name: str | None = None) -> str: return app_name +def rename_path_up_tree(full_path: str | Path, old_name: str, new_name: str) -> Path: + """Rename all instances of `old_name` in the path (file and directories) to `new_name`. + The renaming stops when we reach the directory containing `rxconfig.py`. + + Args: + full_path: The full path to start renaming from. + old_name: The name to be replaced. + new_name: The replacement name. + + Returns: + The updated path after renaming. + """ + current_path = Path(full_path) + new_path = None + + while True: + directory, base = current_path.parent, current_path.name + # Stop renaming when we reach the root dir (which contains rxconfig.py) + if current_path.is_dir() and (current_path / "rxconfig.py").exists(): + new_path = current_path + break + + if old_name == base.removesuffix(constants.Ext.PY): + new_base = base.replace(old_name, new_name) + new_path = directory / new_base + current_path.rename(new_path) + console.debug(f"Renamed {current_path} -> {new_path}") + current_path = new_path + else: + new_path = current_path + + # Move up the directory tree + current_path = directory + + return new_path + + +def rename_app(new_app_name: str, loglevel: constants.LogLevel): + """Rename the app directory. + + Args: + new_app_name: The new name for the app. + loglevel: The log level to use. + + Raises: + Exit: If the command is not ran in the root dir or the app module cannot be imported. + """ + # Set the log level. + console.set_log_level(loglevel) + + if not constants.Config.FILE.exists(): + console.error( + "No rxconfig.py found. Make sure you are in the root directory of your app." + ) + raise typer.Exit(1) + + sys.path.insert(0, str(Path.cwd())) + + config = get_config() + module_path = importlib.util.find_spec(config.module) + if module_path is None: + console.error(f"Could not find module {config.module}.") + raise typer.Exit(1) + + if not module_path.origin: + console.error(f"Could not find origin for module {config.module}.") + raise typer.Exit(1) + console.info(f"Renaming app directory to {new_app_name}.") + process_directory( + Path.cwd(), + config.app_name, + new_app_name, + exclude_dirs=[constants.Dirs.WEB, constants.Dirs.APP_ASSETS], + ) + + rename_path_up_tree(Path(module_path.origin), config.app_name, new_app_name) + + console.success(f"App directory renamed to [bold]{new_app_name}[/bold].") + + +def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: str): + """Rename imports the file using string replacement as well as app_name in rxconfig.py. + + Args: + file_path: The file to process. + old_name: The old name to replace. + new_name: The new name to use. + """ + file_path = Path(file_path) + content = file_path.read_text() + + # Replace `from old_name.` or `from old_name` with `from new_name` + content = re.sub( + rf"\bfrom {re.escape(old_name)}(\b|\.|\s)", + lambda match: f"from {new_name}{match.group(1)}", + content, + ) + + # Replace `import old_name` with `import new_name` + content = re.sub( + rf"\bimport {re.escape(old_name)}\b", + f"import {new_name}", + content, + ) + + # Replace `app_name="old_name"` in rx.Config + content = re.sub( + rf'\bapp_name\s*=\s*["\']{re.escape(old_name)}["\']', + f'app_name="{new_name}"', + content, + ) + + # Replace positional argument `"old_name"` in rx.Config + content = re.sub( + rf'\brx\.Config\(\s*["\']{re.escape(old_name)}["\']', + f'rx.Config("{new_name}"', + content, + ) + + file_path.write_text(content) + + +def process_directory( + directory: str | Path, + old_name: str, + new_name: str, + exclude_dirs: list | None = None, + extensions: list | None = None, +): + """Process files with specified extensions in a directory, excluding specified directories. + + Args: + directory: The root directory to process. + old_name: The old name to replace. + new_name: The new name to use. + exclude_dirs: List of directory names to exclude. Defaults to None. + extensions: List of file extensions to process. + """ + exclude_dirs = exclude_dirs or [] + extensions = extensions or [ + constants.Ext.PY, + constants.Ext.MD, + ] # include .md files, typically used in reflex-web. + extensions_set = {ext.lstrip(".") for ext in extensions} + directory = Path(directory) + + root_exclude_dirs = {directory / exclude_dir for exclude_dir in exclude_dirs} + + files = ( + p.resolve() + for p in directory.glob("**/*") + if p.is_file() and p.suffix.lstrip(".") in extensions_set + ) + + for file_path in files: + if not any( + file_path.is_relative_to(exclude_dir) for exclude_dir in root_exclude_dirs + ): + rename_imports_and_app_name(file_path, old_name, new_name) + + def create_config(app_name: str): """Create a new rxconfig file. @@ -672,7 +884,9 @@ def init_reflex_json(project_hash: int | None): path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json) -def update_next_config(export=False, transpile_packages: Optional[List[str]] = None): +def update_next_config( + export: bool = False, transpile_packages: Optional[List[str]] = None +): """Update Next.js config from Reflex config. Args: @@ -698,7 +912,6 @@ def _update_next_config( next_config = { "basePath": config.frontend_path or "", "compress": config.next_compression, - "reactStrictMode": config.react_strict_mode, "trailingSlash": True, "staticPageGenerationTimeout": config.static_page_generation_timeout, } @@ -835,7 +1048,11 @@ def install_node(): def install_bun(): - """Install bun onto the user's system.""" + """Install bun onto the user's system. + + Raises: + SystemPackageMissingError: If "unzip" is missing. + """ win_supported = is_windows_bun_supported() one_drive_in_path = windows_check_onedrive_in_path() if constants.IS_WINDOWS and (not win_supported or one_drive_in_path): @@ -849,9 +1066,7 @@ def install_bun(): ) # Skip if bun is already installed. - if Path(get_config().bun_path).exists() and get_bun_version() == version.parse( - constants.Bun.VERSION - ): + if get_bun_version() == version.parse(constants.Bun.VERSION): console.debug("Skipping bun installation as it is already installed.") return @@ -872,15 +1087,15 @@ def install_bun(): show_logs=console.is_debug(), ) else: - unzip_path = path_ops.which("unzip") - if unzip_path is None: - raise_system_package_missing_error("unzip") + if path_ops.which("unzip") is None: + raise SystemPackageMissingError("unzip") # Run the bun install script. download_and_run( constants.Bun.INSTALL_URL, f"bun-v{constants.Bun.VERSION}", BUN_INSTALL=str(constants.Bun.ROOT_PATH), + BUN_VERSION=str(constants.Bun.VERSION), ) @@ -914,7 +1129,7 @@ def cached_procedure(cache_file: str, payload_fn: Callable[..., str]): The decorated function. """ - def _inner_decorator(func): + def _inner_decorator(func: Callable): def _inner(*args, **kwargs): payload = _read_cached_procedure_file(cache_file) new_payload = payload_fn(*args, **kwargs) @@ -974,7 +1189,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", @@ -1076,12 +1291,9 @@ def validate_bun(): Raises: Exit: If custom specified bun does not exist or does not meet requirements. """ - # if a custom bun path is provided, make sure its valid - # This is specific to non-FHS OS - bun_path = get_config().bun_path - if path_ops.use_system_bun(): - bun_path = path_ops.which("bun") - if bun_path != constants.Bun.DEFAULT_PATH: + bun_path = path_ops.get_bun_path() + + if bun_path and bun_path.samefile(constants.Bun.DEFAULT_PATH): console.info(f"Using custom Bun path: {bun_path}") bun_version = get_bun_version() if not bun_version: @@ -1099,7 +1311,7 @@ def validate_bun(): raise typer.Exit(1) -def validate_frontend_dependencies(init=True): +def validate_frontend_dependencies(init: bool = True): """Validate frontend dependencies to ensure they meet requirements. Args: @@ -1153,11 +1365,12 @@ def ensure_reflex_installation_id() -> Optional[int]: if installation_id is None: installation_id = random.getrandbits(128) installation_id_file.write_text(str(installation_id)) - # If we get here, installation_id is definitely set - return installation_id except Exception as e: console.debug(f"Failed to ensure reflex installation id: {e}") return None + else: + # If we get here, installation_id is definitely set + return installation_id def initialize_reflex_user_directory(): @@ -1269,7 +1482,7 @@ def prompt_for_template_options(templates: list[Template]) -> 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]: @@ -1371,19 +1584,22 @@ def create_config_init_app_from_remote_template(app_name: str, template_url: str except OSError as ose: console.error(f"Failed to create temp directory for extracting zip: {ose}") raise typer.Exit(1) from ose + try: zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir) # The zip file downloaded from github looks like: # repo-name-branch/**/*, so we need to remove the top level directory. - if len(subdirs := os.listdir(unzip_dir)) != 1: - console.error(f"Expected one directory in the zip, found {subdirs}") - raise typer.Exit(1) - template_dir = unzip_dir / subdirs[0] - console.debug(f"Template folder is located at {template_dir}") except Exception as uze: console.error(f"Failed to unzip the template: {uze}") raise typer.Exit(1) from uze + if len(subdirs := os.listdir(unzip_dir)) != 1: + console.error(f"Expected one directory in the zip, found {subdirs}") + raise typer.Exit(1) + + template_dir = unzip_dir / subdirs[0] + console.debug(f"Template folder is located at {template_dir}") + # Move the rxconfig file here first. path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE) new_config = get_config(reload=True) @@ -1419,7 +1635,9 @@ def initialize_default_app(app_name: str): initialize_app_directory(app_name) -def validate_and_create_app_using_remote_template(app_name, template, templates): +def validate_and_create_app_using_remote_template( + app_name: str, template: str, templates: dict[str, Template] +): """Validate and create an app using a remote template. Args: @@ -1609,7 +1827,7 @@ def initialize_main_module_index_from_generation(app_name: str, generation_hash: generation_hash: The generation hash from reflex.build. Raises: - GeneratedCodeHasNoFunctionDefs: If the fetched code has no function definitions + GeneratedCodeHasNoFunctionDefsError: If the fetched code has no function definitions (the refactored reflex code is expected to have at least one root function defined). """ # Download the reflex code for the generation. @@ -1626,17 +1844,17 @@ def initialize_main_module_index_from_generation(app_name: str, generation_hash: # Determine the name of the last function, which renders the generated code. defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text) if not defined_funcs: - raise GeneratedCodeHasNoFunctionDefs( + raise GeneratedCodeHasNoFunctionDefsError( f"No function definitions found in generated code from {url!r}." ) render_func_name = defined_funcs[-1] - def replace_content(_match): + def replace_content(_match: re.Match) -> str: return "\n".join( [ resp.text, "", - "" "def index() -> rx.Component:", + "def index() -> rx.Component:", f" return {render_func_name}()", "", "", @@ -1661,7 +1879,7 @@ def initialize_main_module_index_from_generation(app_name: str, generation_hash: main_module_path.write_text(main_module_code) -def format_address_width(address_width) -> int | None: +def format_address_width(address_width: str | None) -> int | None: """Cast address width to an int. Args: diff --git a/reflex/utils/processes.py b/reflex/utils/processes.py index 3673b36b2..c92fb7d1a 100644 --- a/reflex/utils/processes.py +++ b/reflex/utils/processes.py @@ -15,13 +15,14 @@ from typing import Callable, Generator, List, Optional, Tuple, Union import psutil import typer from redis.exceptions import RedisError +from rich.progress import Progress from reflex import constants from reflex.config import environment from reflex.utils import console, path_ops, prerequisites -def kill(pid): +def kill(pid: int): """Kill a process. Args: @@ -49,7 +50,7 @@ def get_num_workers() -> int: return (os.cpu_count() or 1) * 2 + 1 -def get_process_on_port(port) -> Optional[psutil.Process]: +def get_process_on_port(port: int) -> Optional[psutil.Process]: """Get the process on the given port. Args: @@ -63,7 +64,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: @@ -72,7 +73,7 @@ def get_process_on_port(port) -> Optional[psutil.Process]: return None -def is_process_on_port(port) -> bool: +def is_process_on_port(port: int) -> bool: """Check if a process is running on the given port. Args: @@ -84,7 +85,7 @@ def is_process_on_port(port) -> bool: return get_process_on_port(port) is not None -def kill_process_on_port(port): +def kill_process_on_port(port: int): """Kill the process on the given port. Args: @@ -92,10 +93,10 @@ 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: +def change_port(port: int, _type: str) -> int: """Change the port. Args: @@ -106,7 +107,7 @@ def change_port(port: str, _type: str) -> str: The new port. """ - new_port = str(int(port) + 1) + new_port = port + 1 if is_process_on_port(new_port): return change_port(new_port, _type) console.info( @@ -115,7 +116,7 @@ def change_port(port: str, _type: str) -> str: return new_port -def handle_port(service_name: str, port: str, default_port: str) -> str: +def handle_port(service_name: str, port: int, default_port: int) -> int: """Change port if the specified port is in use and is not explicitly specified as a CLI arg or config arg. otherwise tell the user the port is in use and exit the app. @@ -134,7 +135,7 @@ def handle_port(service_name: str, port: str, default_port: str) -> str: Exit:when the port is in use. """ if is_process_on_port(port): - if int(port) == int(default_port): + if port == int(default_port): return change_port(port, service_name) else: console.error(f"{service_name.capitalize()} port: {port} is already in use") @@ -142,7 +143,12 @@ def handle_port(service_name: str, port: str, default_port: str) -> str: return port -def new_process(args, run: bool = False, show_logs: bool = False, **kwargs): +def new_process( + args: str | list[str] | list[str | None] | list[str | Path | None], + run: bool = False, + show_logs: bool = False, + **kwargs, +): """Wrapper over subprocess.Popen to unify the launch of child processes. Args: @@ -158,7 +164,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs): Exit: When attempting to run a command with a None value. """ # Check for invalid command first. - if None in args: + if isinstance(args, list) and None in args: console.error(f"Invalid command: {args}") raise typer.Exit(1) @@ -192,7 +198,7 @@ def new_process(args, run: bool = False, show_logs: bool = False, **kwargs): } console.debug(f"Running command: {args}") fn = subprocess.run if run else subprocess.Popen - return fn(args, **kwargs) + return fn(args, **kwargs) # pyright: ignore [reportCallIssue, reportArgumentType] @contextlib.contextmanager @@ -213,14 +219,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 @@ -248,7 +254,7 @@ def run_concurrently(*fns: Union[Callable, Tuple]) -> None: def stream_logs( message: str, process: subprocess.Popen, - progress=None, + progress: Progress | None = None, suppress_errors: bool = False, analytics_enabled: bool = False, ): @@ -368,7 +374,7 @@ def get_command_with_loglevel(command: list[str]) -> list[str]: The updated command list """ npm_path = path_ops.get_npm_path() - npm_path = str(Path(npm_path).resolve()) if npm_path else npm_path + npm_path = str(npm_path) if npm_path else None if command[0] == npm_path: return [*command, "--loglevel", "silly"] @@ -376,10 +382,10 @@ def get_command_with_loglevel(command: list[str]) -> list[str]: def run_process_with_fallback( - args, + args: list[str], *, - show_status_message, - fallback=None, + show_status_message: str, + fallback: str | list | None = None, analytics_enabled: bool = False, **kwargs, ): @@ -418,7 +424,7 @@ def run_process_with_fallback( ) -def execute_command_and_return_output(command) -> str | None: +def execute_command_and_return_output(command: str) -> str | None: """Execute a command and return the output. Args: diff --git a/reflex/utils/pyi_generator.py b/reflex/utils/pyi_generator.py index 152c06949..bd9c94a6e 100644 --- a/reflex/utils/pyi_generator.py +++ b/reflex/utils/pyi_generator.py @@ -83,7 +83,7 @@ DEFAULT_IMPORTS = { } -def _walk_files(path): +def _walk_files(path: str | Path): """Walk all files in a path. This can be replaced with Path.walk() in python3.12. @@ -114,7 +114,9 @@ def _relative_to_pwd(path: Path) -> Path: return path -def _get_type_hint(value, type_hint_globals, is_optional=True) -> str: +def _get_type_hint( + value: Any, type_hint_globals: dict, is_optional: bool = True +) -> str: """Resolve the type hint for value. Args: @@ -229,7 +231,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 +369,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( ( @@ -383,7 +385,7 @@ def _extract_class_props_as_ast_nodes( return kwargs -def type_to_ast(typ, cls: type) -> ast.AST: +def type_to_ast(typ: Any, cls: type) -> ast.AST: """Converts any type annotation into its AST representation. Handles nested generic types, unions, etc. @@ -434,14 +436,16 @@ 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(), ) -def _get_parent_imports(func): +def _get_parent_imports(func: Callable): _imports = {"reflex.vars": ["Var"]} for type_hint in inspect.get_annotations(func).values(): try: @@ -575,7 +579,7 @@ def _generate_component_create_functiondef( 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( @@ -618,10 +622,10 @@ def _generate_component_create_functiondef( defaults=[], ) - definition = ast.FunctionDef( + definition = ast.FunctionDef( # pyright: ignore [reportCallIssue] name="create", args=create_args, - body=[ + body=[ # pyright: ignore [reportArgumentType] ast.Expr( value=ast.Constant( value=_generate_docstrings( @@ -630,7 +634,7 @@ def _generate_component_create_functiondef( ), ), ast.Expr( - value=ast.Ellipsis(), + value=ast.Constant(value=Ellipsis), ), ], decorator_list=[ @@ -641,7 +645,7 @@ def _generate_component_create_functiondef( 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 @@ -680,7 +684,7 @@ def _generate_staticmethod_call_functiondef( else [] ), ) - definition = ast.FunctionDef( + definition = ast.FunctionDef( # pyright: ignore [reportCallIssue] name="__call__", args=call_args, body=[ @@ -690,7 +694,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 +730,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 +820,7 @@ class StubGenerator(ast.NodeTransformer): 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 +918,7 @@ class StubGenerator(ast.NodeTransformer): 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 +945,9 @@ class StubGenerator(ast.NodeTransformer): 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: @@ -1050,7 +1054,7 @@ class PyiGenerator: pyi_path.write_text(pyi_content) logger.info(f"Wrote {relpath}") - def _get_init_lazy_imports(self, mod, new_tree): + def _get_init_lazy_imports(self, mod: tuple | ModuleType, new_tree: ast.AST): # retrieve the _SUBMODULES and _SUBMOD_ATTRS from an init file if present. sub_mods = getattr(mod, "_SUBMODULES", None) sub_mod_attrs = getattr(mod, "_SUBMOD_ATTRS", None) @@ -1077,7 +1081,7 @@ class PyiGenerator: + ( " # 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 "" ) @@ -1136,7 +1140,7 @@ class PyiGenerator: if pyi_path: self.written_files.append(pyi_path) - def scan_all(self, targets, changed_files: list[Path] | None = None): + def scan_all(self, targets: list, changed_files: list[Path] | None = None): """Scan all targets for class inheriting Component and generate the .pyi files. Args: diff --git a/reflex/utils/registry.py b/reflex/utils/registry.py index d98178c61..47727d659 100644 --- a/reflex/utils/registry.py +++ b/reflex/utils/registry.py @@ -22,15 +22,15 @@ def latency(registry: str) -> int: return 10_000_000 -def average_latency(registry, attempts: int = 3) -> int: +def average_latency(registry: str, attempts: int = 3) -> int: """Get the average latency of a registry. Args: - registry (str): The URL of the registry. - attempts (int): The number of attempts to make. Defaults to 10. + registry: The URL of the registry. + attempts: The number of attempts to make. Defaults to 10. Returns: - int: The average latency of the registry in microseconds. + The average latency of the registry in microseconds. """ return sum(latency(registry) for _ in range(attempts)) // attempts diff --git a/reflex/utils/serializers.py b/reflex/utils/serializers.py index 4bb8dea92..f78438522 100644 --- a/reflex/utils/serializers.py +++ b/reflex/utils/serializers.py @@ -476,7 +476,7 @@ try: 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/telemetry.py b/reflex/utils/telemetry.py index fc90932a6..ecfd52428 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -122,7 +122,7 @@ def _prepare_event(event: str, **kwargs) -> dict: return {} if UTC is None: - # for python 3.9 & 3.10 + # for python 3.10 stamp = datetime.utcnow().isoformat() else: # for python 3.11 & 3.12 @@ -156,12 +156,13 @@ def _prepare_event(event: str, **kwargs) -> dict: def _send_event(event_data: dict) -> bool: try: httpx.post(POSTHOG_API_URL, json=event_data) - return True except Exception: return False + else: + return True -def _send(event, telemetry_enabled, **kwargs): +def _send(event: str, telemetry_enabled: bool | None, **kwargs): from reflex.config import get_config # Get the telemetry_enabled from the config if it is not specified. @@ -188,7 +189,7 @@ def send(event: str, telemetry_enabled: bool | None = None, **kwargs): kwargs: Additional data to send with the event. """ - async def async_send(event, telemetry_enabled, **kwargs): + async def async_send(event: str, telemetry_enabled: bool | None, **kwargs): return _send(event, telemetry_enabled, **kwargs) try: diff --git a/reflex/utils/types.py b/reflex/utils/types.py index b8bcbf2d6..58fec8f3b 100644 --- a/reflex/utils/types.py +++ b/reflex/utils/types.py @@ -24,7 +24,7 @@ from typing import ( Tuple, Type, Union, - _GenericAlias, # type: ignore + _GenericAlias, # pyright: ignore [reportAttributeAccessIssue] get_args, get_type_hints, ) @@ -39,7 +39,9 @@ from reflex.components.core.breakpoints import Breakpoints 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 @@ GenericAliasTypes = [_GenericAlias] 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) @@ -153,7 +157,7 @@ class Unset: @lru_cache() -def get_origin(tp): +def get_origin(tp: Any): """Get the origin of a class. Args: @@ -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: @@ -236,7 +240,7 @@ def is_literal(cls: GenericType) -> bool: return get_origin(cls) is Literal -def has_args(cls) -> bool: +def has_args(cls: Type) -> bool: """Check if the class has generic parameters. Args: @@ -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 @@ -605,7 +609,9 @@ def _isinstance(obj: Any, cls: GenericType, nested: bool = False) -> bool: return ( isinstance(obj, tuple) and len(obj) == len(args) - and all(_isinstance(item, arg) for item, arg in zip(obj, args)) + and all( + _isinstance(item, arg) for item, arg in zip(obj, args, strict=True) + ) ) if origin in (dict, Breakpoints): return isinstance(obj, dict) and all( @@ -747,7 +753,7 @@ def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool: return type_ in allowed_types -def is_encoded_fstring(value) -> bool: +def is_encoded_fstring(value: Any) -> bool: """Check if a value is an encoded Var f-string. Args: @@ -790,7 +796,7 @@ def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str): ) -def validate_parameter_literals(func): +def validate_parameter_literals(func: Callable): """Decorator to check that the arguments passed to a function correspond to the correct function parameter if it (the parameter) is a literal type. @@ -808,7 +814,7 @@ def validate_parameter_literals(func): annotations = {param[0]: param[1].annotation for param in func_params} # validate args - for param, arg in zip(annotations, args): + for param, arg in zip(annotations, args, strict=False): if annotations[param] is inspect.Parameter.empty: continue validate_literal(param, arg, annotations[param], func.__name__) @@ -829,6 +835,22 @@ StateBases = get_base_class(StateVar) StateIterBases = get_base_class(StateIterVar) +def safe_issubclass(cls: Type, cls_check: Type | Tuple[Type, ...]): + """Check if a class is a subclass of another class. Returns False if internal error occurs. + + Args: + cls: The class to check. + cls_check: The class to check against. + + Returns: + Whether the class is a subclass of the other class. + """ + try: + return issubclass(cls, cls_check) + except TypeError: + return False + + def typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> bool: """Check if a type hint is a subclass of another type hint. @@ -890,6 +912,8 @@ def typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> boo # It also ignores when the length of the arguments is different return all( typehint_issubclass(provided_arg, accepted_arg) - for provided_arg, accepted_arg in zip(provided_args, accepted_args) + for provided_arg, accepted_arg in zip( + provided_args, accepted_args, strict=False + ) if accepted_arg is not Any ) diff --git a/reflex/vars/base.py b/reflex/vars/base.py index 2892d004d..ec65c3711 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -5,14 +5,13 @@ from __future__ import annotations import contextlib import dataclasses import datetime -import dis import functools import inspect import json import random import re import string -import sys +import uuid import warnings from types import CodeType, FunctionType from typing import ( @@ -20,14 +19,17 @@ from typing import ( Any, Callable, ClassVar, + Coroutine, Dict, FrozenSet, Generic, Iterable, List, Literal, + Mapping, NoReturn, Optional, + Sequence, Set, Tuple, Type, @@ -45,10 +47,10 @@ from reflex.base import Base from reflex.constants.compiler import Hooks from reflex.utils import console, exceptions, imports, serializers, types from reflex.utils.exceptions import ( + UntypedComputedVarError, VarAttributeError, VarDependencyError, VarTypeError, - VarValueError, ) from reflex.utils.format import format_state_name from reflex.utils.imports import ( @@ -64,6 +66,7 @@ from reflex.utils.types import ( _isinstance, get_origin, has_args, + safe_issubclass, unionize, ) @@ -77,6 +80,8 @@ if TYPE_CHECKING: VAR_TYPE = TypeVar("VAR_TYPE", covariant=True) OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE") +STRING_T = TypeVar("STRING_T", bound=str) +SEQUENCE_TYPE = TypeVar("SEQUENCE_TYPE", bound=Sequence) warnings.filterwarnings("ignore", message="fields may not start with an underscore") @@ -127,7 +132,7 @@ class VarData: state: str = "", field_name: str = "", imports: ImportDict | ParsedImportDict | None = None, - hooks: dict[str, VarData | None] | None = None, + hooks: Mapping[str, VarData | None] | Sequence[str] | str | None = None, deps: list[Var] | None = None, position: Hooks.HookPosition | None = None, ): @@ -141,10 +146,12 @@ class VarData: deps: Dependencies of the var for useCallback. position: Position of the hook in the component. """ + if isinstance(hooks, str): + hooks = [hooks] + if not isinstance(hooks, dict): + hooks = {hook: None for hook in (hooks or [])} immutable_imports: ImmutableParsedImportDict = tuple( - sorted( - ((k, tuple(sorted(v))) for k, v in parse_imports(imports or {}).items()) - ) + (k, tuple(v)) for k, v in parse_imports(imports or {}).items() ) object.__setattr__(self, "state", state) object.__setattr__(self, "field_name", field_name) @@ -153,6 +160,16 @@ class VarData: object.__setattr__(self, "deps", tuple(deps or [])) object.__setattr__(self, "position", position or None) + if hooks and any(hooks.values()): + merged_var_data = VarData.merge(self, *hooks.values()) + if merged_var_data is not None: + object.__setattr__(self, "state", merged_var_data.state) + object.__setattr__(self, "field_name", merged_var_data.field_name) + object.__setattr__(self, "imports", merged_var_data.imports) + object.__setattr__(self, "hooks", merged_var_data.hooks) + object.__setattr__(self, "deps", merged_var_data.deps) + object.__setattr__(self, "position", merged_var_data.position) + def old_school_imports(self) -> ImportDict: """Return the imports as a mutable dict. @@ -432,7 +449,7 @@ class Var(Generic[VAR_TYPE]): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ToVarOperation(ToOperation, cls): """Base class of converting a var to another var type.""" @@ -443,7 +460,12 @@ class Var(Generic[VAR_TYPE]): _default_var_type: ClassVar[GenericType] = default_type - ToVarOperation.__name__ = f'To{cls.__name__.removesuffix("Var")}Operation' + new_to_var_operation_name = f"To{cls.__name__.removesuffix('Var')}Operation" + ToVarOperation.__qualname__ = ( + ToVarOperation.__qualname__.removesuffix(ToVarOperation.__name__) + + new_to_var_operation_name + ) + ToVarOperation.__name__ = new_to_var_operation_name _var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types)) @@ -492,20 +514,30 @@ class Var(Generic[VAR_TYPE]): @overload def _replace( - self, _var_type: Type[OTHER_VAR_TYPE], merge_var_data=None, **kwargs: Any + self, + _var_type: Type[OTHER_VAR_TYPE], + merge_var_data: VarData | None = None, + **kwargs: Any, ) -> Var[OTHER_VAR_TYPE]: ... @overload def _replace( - self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any + self, + _var_type: GenericType | None = None, + merge_var_data: VarData | None = None, + **kwargs: Any, ) -> Self: ... def _replace( - self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any + self, + _var_type: GenericType | None = None, + merge_var_data: VarData | None = None, + **kwargs: Any, ) -> Self | Var: """Make a copy of this Var with updated fields. Args: + _var_type: The new type of the Var. merge_var_data: VarData to merge into the existing VarData. **kwargs: Var fields to update. @@ -539,56 +571,89 @@ class Var(Generic[VAR_TYPE]): return value_with_replaced + @overload + @classmethod + def create( # type: ignore[override] + cls, + value: bool, + _var_data: VarData | None = None, + ) -> BooleanVar: ... + + @overload + @classmethod + def create( # type: ignore[override] + cls, + value: int, + _var_data: VarData | None = None, + ) -> NumberVar[int]: ... + + @overload @classmethod def create( cls, - value: Any, - _var_is_local: bool | None = None, - _var_is_string: bool | None = None, + value: float, _var_data: VarData | None = None, - ) -> Var: + ) -> NumberVar[float]: ... + + @overload + @classmethod + def create( # pyright: ignore [reportOverlappingOverload] + cls, + value: STRING_T, + _var_data: VarData | None = None, + ) -> StringVar[STRING_T]: ... + + @overload + @classmethod + def create( + cls, + value: None, + _var_data: VarData | None = None, + ) -> NoneVar: ... + + @overload + @classmethod + def create( + cls, + value: MAPPING_TYPE, + _var_data: VarData | None = None, + ) -> ObjectVar[MAPPING_TYPE]: ... + + @overload + @classmethod + def create( + cls, + value: SEQUENCE_TYPE, + _var_data: VarData | None = None, + ) -> ArrayVar[SEQUENCE_TYPE]: ... + + @overload + @classmethod + def create( + cls, + value: OTHER_VAR_TYPE, + _var_data: VarData | None = None, + ) -> Var[OTHER_VAR_TYPE]: ... + + @classmethod + def create( + cls, + value: OTHER_VAR_TYPE, + _var_data: VarData | None = None, + ) -> Var[OTHER_VAR_TYPE]: """Create a var from a value. Args: value: The value to create the var from. - _var_is_local: Whether the var is local. Deprecated. - _var_is_string: Whether the var is a string literal. Deprecated. _var_data: Additional hooks and imports associated with the Var. Returns: The var. """ - if _var_is_local is not None: - console.deprecate( - feature_name="_var_is_local", - reason="The _var_is_local argument is not supported for Var. " - "If you want to create a Var from a raw Javascript expression, use the constructor directly", - deprecation_version="0.6.0", - removal_version="0.7.0", - ) - if _var_is_string is not None: - console.deprecate( - feature_name="_var_is_string", - reason="The _var_is_string argument is not supported for Var. " - "If you want to create a Var from a raw Javascript expression, use the constructor directly", - deprecation_version="0.6.0", - removal_version="0.7.0", - ) - # If the value is already a var, do nothing. if isinstance(value, Var): return value - # Try to pull the imports and hooks from contained values. - if not isinstance(value, str): - return LiteralVar.create(value, _var_data=_var_data) - - if _var_is_string is False or _var_is_local is True: - return cls( - _js_expr=value, - _var_data=_var_data, - ) - return LiteralVar.create(value, _var_data=_var_data) @classmethod @@ -643,8 +708,8 @@ class Var(Generic[VAR_TYPE]): @overload def to( self, - output: type[dict], - ) -> ObjectVar[dict]: ... + output: type[MAPPING_TYPE], + ) -> ObjectVar[MAPPING_TYPE]: ... @overload def to( @@ -686,14 +751,16 @@ class Var(Generic[VAR_TYPE]): # If the first argument is a python type, we map it to the corresponding Var type. for var_subclass in _var_subclasses[::-1]: - if fixed_output_type in var_subclass.python_types: + if fixed_output_type in var_subclass.python_types or safe_issubclass( + fixed_output_type, var_subclass.python_types + ): 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): + if can_use_in_object_var(output): return self.to(ObjectVar, output) if inspect.isclass(output): @@ -707,7 +774,7 @@ class Var(Generic[VAR_TYPE]): 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: @@ -725,6 +792,9 @@ class Var(Generic[VAR_TYPE]): return self + @overload + def guess_type(self: Var[NoReturn]) -> Var[Any]: ... # pyright: ignore [reportOverlappingOverload] + @overload def guess_type(self: Var[str]) -> StringVar: ... @@ -734,6 +804,9 @@ class Var(Generic[VAR_TYPE]): @overload def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ... + @overload + def guess_type(self: Var[BASE_TYPE]) -> ObjectVar[BASE_TYPE]: ... + @overload def guess_type(self) -> Self: ... @@ -820,7 +893,7 @@ class Var(Generic[VAR_TYPE]): return False if issubclass(type_, list): return [] - if issubclass(type_, dict): + if issubclass(type_, Mapping): return {} if issubclass(type_, tuple): return () @@ -882,7 +955,7 @@ class Var(Generic[VAR_TYPE]): return setter - def _var_set_state(self, state: type[BaseState] | str): + def _var_set_state(self, state: type[BaseState] | str) -> Self: """Set the state of the var. Args: @@ -897,7 +970,7 @@ class Var(Generic[VAR_TYPE]): else format_state_name(state.get_full_name()) ) - return StateOperation.create( + return StateOperation.create( # pyright: ignore [reportReturnType] formatted_state_name, self, _var_data=VarData.merge( @@ -1026,7 +1099,7 @@ class Var(Generic[VAR_TYPE]): f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")] } ), - ).to(ObjectVar, Dict[str, str]) + ).to(ObjectVar, Mapping[str, str]) return refs[LiteralVar.create(str(self))] @deprecated("Use `.js_type()` instead.") @@ -1076,43 +1149,6 @@ class Var(Generic[VAR_TYPE]): """ return self - def __getattr__(self, name: str): - """Get an attribute of the var. - - Args: - name: The name of the attribute. - - Returns: - The attribute. - - Raises: - VarAttributeError: If the attribute does not exist. - TypeError: If the var type is Any. - """ - if name.startswith("_"): - return self.__getattribute__(name) - - if name == "contains": - raise TypeError( - f"Var of type {self._var_type} does not support contains check." - ) - if name == "reverse": - raise TypeError("Cannot reverse non-list var.") - - if self._var_type is Any: - raise TypeError( - f"You must provide an annotation for the state var `{self!s}`. Annotation cannot be `{self._var_type}`." - ) - - if name in REPLACED_NAMES: - raise VarAttributeError( - f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}" - ) - - raise VarAttributeError( - f"The State var has no attribute '{name}' or may have been annotated wrongly.", - ) - def _decode(self) -> Any: """Decode Var as a python value. @@ -1123,7 +1159,7 @@ class Var(Generic[VAR_TYPE]): 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: @@ -1174,36 +1210,76 @@ class Var(Generic[VAR_TYPE]): return ArrayVar.range(first_endpoint, second_endpoint, step) - def __bool__(self) -> bool: - """Raise exception if using Var in a boolean context. + if not TYPE_CHECKING: - Raises: - VarTypeError: when attempting to bool-ify the Var. - """ - raise VarTypeError( - f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. " - "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)." - ) + def __getattr__(self, name: str): + """Get an attribute of the var. - def __iter__(self) -> Any: - """Raise exception if using Var in an iterable context. + Args: + name: The name of the attribute. - Raises: - VarTypeError: when attempting to iterate over the Var. - """ - raise VarTypeError( - f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`." - ) + Raises: + VarAttributeError: If the attribute does not exist. + UntypedVarError: If the var type is Any. + TypeError: If the var type is Any. - def __contains__(self, _: Any) -> Var: - """Override the 'in' operator to alert the user that it is not supported. + # noqa: DAR101 self + """ + if name.startswith("_"): + raise VarAttributeError(f"Attribute {name} not found.") - Raises: - VarTypeError: the operation is not supported - """ - raise VarTypeError( - "'in' operator not supported for Var types, use Var.contains() instead." - ) + if name == "contains": + raise TypeError( + f"Var of type {self._var_type} does not support contains check." + ) + if name == "reverse": + raise TypeError("Cannot reverse non-list var.") + + if self._var_type is Any: + raise exceptions.UntypedVarError( + f"You must provide an annotation for the state var `{self!s}`. Annotation cannot be `{self._var_type}`." + ) + + raise VarAttributeError( + f"The State var has no attribute '{name}' or may have been annotated wrongly.", + ) + + def __bool__(self) -> bool: + """Raise exception if using Var in a boolean context. + + Raises: + VarTypeError: when attempting to bool-ify the Var. + + # noqa: DAR101 self + """ + raise VarTypeError( + f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. " + "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)." + ) + + def __iter__(self) -> Any: + """Raise exception if using Var in an iterable context. + + Raises: + VarTypeError: when attempting to iterate over the Var. + + # noqa: DAR101 self + """ + raise VarTypeError( + f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`." + ) + + def __contains__(self, _: Any) -> Var: + """Override the 'in' operator to alert the user that it is not supported. + + Raises: + VarTypeError: the operation is not supported + + # noqa: DAR101 self + """ + raise VarTypeError( + "'in' operator not supported for Var types, use Var.contains() instead." + ) OUTPUT = TypeVar("OUTPUT", bound=Var) @@ -1250,7 +1326,7 @@ class ToOperation: """ return VarData.merge( self._original._get_all_var_data(), - self._var_data, # type: ignore + self._var_data, ) @classmethod @@ -1271,10 +1347,10 @@ class ToOperation: 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] ) @@ -1336,7 +1412,7 @@ class LiteralVar(Var): _var_literal_subclasses.append((cls, var_subclass)) @classmethod - def create( + def create( # pyright: ignore [reportArgumentType] cls, value: Any, _var_data: VarData | None = None, @@ -1354,7 +1430,7 @@ class LiteralVar(Var): TypeError: If the value is not a supported type for LiteralVar. """ from .object import LiteralObjectVar - from .sequence import LiteralStringVar + from .sequence import ArrayVar, LiteralStringVar if isinstance(value, Var): if _var_data is None: @@ -1373,7 +1449,7 @@ class LiteralVar(Var): serialized_value = serializers.serialize(value) if serialized_value is not None: - if isinstance(serialized_value, dict): + if isinstance(serialized_value, Mapping): return LiteralObjectVar.create( serialized_value, _var_type=type(value), @@ -1410,6 +1486,9 @@ class LiteralVar(Var): _var_data=_var_data, ) + if isinstance(value, range): + return ArrayVar.range(value.start, value.stop, value.step) + raise TypeError( f"Unsupported type {type(value)} for LiteralVar. Tried to create a LiteralVar from {value}." ) @@ -1417,6 +1496,12 @@ class LiteralVar(Var): def __post_init__(self): """Post-initialize the var.""" + @property + def _var_value(self) -> Any: + raise NotImplementedError( + "LiteralVar subclasses must implement the _var_value property." + ) + def json(self) -> str: """Serialize the var to a JSON string. @@ -1463,7 +1548,7 @@ T = TypeVar("T") # 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]: ... @@ -1489,7 +1574,7 @@ def var_operation( ) -> Callable[P, StringVar]: ... -LIST_T = TypeVar("LIST_T", bound=Union[List[Any], Tuple, Set]) +LIST_T = TypeVar("LIST_T", bound=Sequence) @overload @@ -1498,7 +1583,7 @@ def var_operation( ) -> Callable[P, ArrayVar[LIST_T]]: ... -OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Dict) +OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Mapping) @overload @@ -1513,7 +1598,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. @@ -1547,7 +1632,7 @@ def var_operation( 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 @@ -1573,25 +1658,100 @@ def figure_out_type(value: Any) -> types.GenericType: return Set[unionize(*(figure_out_type(v) for v in value))] if isinstance(value, tuple): return Tuple[unionize(*(figure_out_type(v) for v in value)), ...] - if isinstance(value, dict): - return Dict[ + if isinstance(value, Mapping): + return Mapping[ unionize(*(figure_out_type(k) for k in value)), unionize(*(figure_out_type(v) for v in value.values())), ] return type(value) -class cached_property_no_lock(functools.cached_property): - """A special version of functools.cached_property that does not use a lock.""" +GLOBAL_CACHE = {} - def __init__(self, func): - """Initialize the cached_property_no_lock. + +class cached_property: # noqa: N801 + """A cached property that caches the result of the function.""" + + def __init__(self, func: Callable): + """Initialize the cached_property. Args: func: The function to cache. """ - super().__init__(func) - self.lock = contextlib.nullcontext() + self._func = func + self._attrname = None + + def __set_name__(self, owner: Any, name: str): + """Set the name of the cached property. + + Args: + owner: The owner of the cached property. + name: The name of the cached property. + + Raises: + TypeError: If the cached property is assigned to two different names. + """ + if self._attrname is None: + self._attrname = name + + original_del = getattr(owner, "__del__", None) + + def delete_property(this: Any): + """Delete the cached property. + + Args: + this: The object to delete the cached property from. + """ + cached_field_name = "_reflex_cache_" + name + try: + unique_id = object.__getattribute__(this, cached_field_name) + except AttributeError: + if original_del is not None: + original_del(this) + return + if unique_id in GLOBAL_CACHE: + del GLOBAL_CACHE[unique_id] + + if original_del is not None: + original_del(this) + + owner.__del__ = delete_property + + elif name != self._attrname: + raise TypeError( + "Cannot assign the same cached_property to two different names " + f"({self._attrname!r} and {name!r})." + ) + + def __get__(self, instance: Any, owner: Type | None = None): + """Get the cached property. + + Args: + instance: The instance to get the cached property from. + owner: The owner of the cached property. + + Returns: + The cached property. + + Raises: + TypeError: If the class does not have __set_name__. + """ + if self._attrname is None: + raise TypeError( + "Cannot use cached_property on a class without __set_name__." + ) + cached_field_name = "_reflex_cache_" + self._attrname + try: + unique_id = object.__getattribute__(instance, cached_field_name) + except AttributeError: + unique_id = uuid.uuid4().int + object.__setattr__(instance, cached_field_name, unique_id) + if unique_id not in GLOBAL_CACHE: + GLOBAL_CACHE[unique_id] = self._func(instance) + return GLOBAL_CACHE[unique_id] + + +cached_property_no_lock = cached_property class CachedVarOperation: @@ -1617,7 +1777,7 @@ class CachedVarOperation: 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. @@ -1639,7 +1799,7 @@ class CachedVarOperation: 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, @@ -1656,7 +1816,7 @@ class CachedVarOperation: 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"] ], ) @@ -1673,7 +1833,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 @@ -1703,7 +1863,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 @@ -1726,7 +1886,7 @@ def _or_operation(a: Var, b: Var): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class CallableVar(Var): """Decorate a Var-returning function to act as both a Var and a function. @@ -1757,7 +1917,7 @@ class CallableVar(Var): object.__setattr__(self, "fn", fn) object.__setattr__(self, "original_var", original_var) - def __call__(self, *args, **kwargs) -> Var: + def __call__(self, *args: Any, **kwargs: Any) -> Var: """Call the decorated function. Args: @@ -1807,7 +1967,7 @@ def is_computed_var(obj: Any) -> TypeGuard[ComputedVar]: @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ComputedVar(Var[RETURN_TYPE]): """A field with computed getters.""" @@ -1822,7 +1982,7 @@ class ComputedVar(Var[RETURN_TYPE]): _initial_value: RETURN_TYPE | types.Unset = dataclasses.field(default=types.Unset()) # Explicit var dependencies to track - _static_deps: set[str] = dataclasses.field(default_factory=set) + _static_deps: dict[str, set[str]] = dataclasses.field(default_factory=dict) # Whether var dependencies should be auto-determined _auto_deps: bool = dataclasses.field(default=True) @@ -1832,7 +1992,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, @@ -1859,19 +2019,14 @@ class ComputedVar(Var[RETURN_TYPE]): Raises: TypeError: If the computed var dependencies are not Var instances or var names. + UntypedComputedVarError: If the computed var is untyped. """ hint = kwargs.pop("return_type", None) or get_type_hints(fget).get( "return", Any ) if hint is Any: - console.deprecate( - "untyped-computed-var", - "ComputedVar should have a return type annotation.", - "0.6.5", - "0.7.0", - ) - + raise UntypedComputedVarError(var_name=fget.__name__) kwargs.setdefault("_js_expr", fget.__name__) kwargs.setdefault("_var_type", hint) @@ -1897,31 +2052,50 @@ class ComputedVar(Var[RETURN_TYPE]): object.__setattr__(self, "_update_interval", interval) - if deps is None: - deps = [] - else: + _static_deps = {} + if isinstance(deps, dict): + # Assume a dict is coming from _replace, so no special processing. + _static_deps = deps + elif deps is not None: for dep in deps: if isinstance(dep, Var): - continue - if isinstance(dep, str) and dep != "": - continue - raise TypeError( - "ComputedVar dependencies must be Var instances or var names (non-empty strings)." - ) + state_name = ( + all_var_data.state + if (all_var_data := dep._get_all_var_data()) + and all_var_data.state + else None + ) + if all_var_data is not None: + var_name = all_var_data.field_name + else: + var_name = dep._js_expr + _static_deps.setdefault(state_name, set()).add(var_name) + elif isinstance(dep, str) and dep != "": + _static_deps.setdefault(None, set()).add(dep) + else: + raise TypeError( + "ComputedVar dependencies must be Var instances or var names (non-empty strings)." + ) object.__setattr__( self, "_static_deps", - {dep._js_expr if isinstance(dep, Var) else dep for dep in deps}, + _static_deps, ) object.__setattr__(self, "_auto_deps", auto_deps) object.__setattr__(self, "_fget", fget) @override - def _replace(self, merge_var_data=None, **kwargs: Any) -> Self: + def _replace( + self, + _var_type: Any = None, + merge_var_data: VarData | None = None, + **kwargs: Any, + ) -> Self: """Replace the attributes of the ComputedVar. Args: + _var_type: ignored in ComputedVar. merge_var_data: VarData to merge into the existing VarData. **kwargs: Var fields to update. @@ -1944,6 +2118,7 @@ class ComputedVar(Var[RETURN_TYPE]): "_var_data": kwargs.pop( "_var_data", VarData.merge(self._var_data, merge_var_data) ), + "return_type": kwargs.pop("return_type", self._var_type), } if kwargs: @@ -1986,6 +2161,13 @@ class ComputedVar(Var[RETURN_TYPE]): return True return datetime.datetime.now() - last_updated > self._update_interval + @overload + def __get__( + self: ComputedVar[bool], + instance: None, + owner: Type, + ) -> BooleanVar: ... + @overload def __get__( self: ComputedVar[int] | ComputedVar[float], @@ -2002,10 +2184,10 @@ class ComputedVar(Var[RETURN_TYPE]): @overload def __get__( - self: ComputedVar[dict[DICT_KEY, DICT_VAL]], + self: ComputedVar[Mapping[DICT_KEY, DICT_VAL]], instance: None, owner: Type, - ) -> ObjectVar[dict[DICT_KEY, DICT_VAL]]: ... + ) -> ObjectVar[Mapping[DICT_KEY, DICT_VAL]]: ... @overload def __get__( @@ -2014,13 +2196,6 @@ class ComputedVar(Var[RETURN_TYPE]): owner: Type, ) -> ArrayVar[list[LIST_INSIDE]]: ... - @overload - def __get__( - self: ComputedVar[set[LIST_INSIDE]], - instance: None, - owner: Type, - ) -> ArrayVar[set[LIST_INSIDE]]: ... - @overload def __get__( self: ComputedVar[tuple[LIST_INSIDE, ...]], @@ -2034,7 +2209,7 @@ class ComputedVar(Var[RETURN_TYPE]): @overload def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ... - def __get__(self, instance: BaseState | None, owner): + def __get__(self, instance: BaseState | None, owner: Type): """Get the ComputedVar value. If the value is already cached on the instance, return the cached value. @@ -2077,130 +2252,69 @@ class ComputedVar(Var[RETURN_TYPE]): setattr(instance, self._last_updated_attr, datetime.datetime.now()) value = getattr(instance, self._cache_attr) - if not _isinstance(value, self._var_type): - console.deprecate( - "mismatched-computed-var-return", - f"Computed var {type(instance).__name__}.{self._js_expr} returned value of type {type(value)}, " - f"expected {self._var_type}. This might cause unexpected behavior.", - "0.6.5", - "0.7.0", - ) + self._check_deprecated_return_type(instance, value) return value + def _check_deprecated_return_type(self, instance: BaseState, value: Any) -> None: + if not _isinstance(value, self._var_type): + console.error( + f"Computed var '{type(instance).__name__}.{self._js_expr}' must return" + f" type '{self._var_type}', got '{type(value)}'." + ) + def _deps( self, - objclass: Type, + objclass: Type[BaseState], obj: FunctionType | CodeType | None = None, - self_name: Optional[str] = None, - ) -> set[str]: + ) -> dict[str, set[str]]: """Determine var dependencies of this ComputedVar. - Save references to attributes accessed on "self". Recursively called - when the function makes a method call on "self" or define comprehensions - or nested functions that may reference "self". + Save references to attributes accessed on "self" or other fetched states. + + Recursively called when the function makes a method call on "self" or + define comprehensions or nested functions that may reference "self". Args: objclass: the class obj this ComputedVar is attached to. obj: the object to disassemble (defaults to the fget function). - self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions. Returns: - A set of variable names accessed by the given obj. - - Raises: - VarValueError: if the function references the get_state, parent_state, or substates attributes - (cannot track deps in a related state, only implicitly via parent state). + A dictionary mapping state names to the set of variable names + accessed by the given obj. """ + from .dep_tracking import DependencyTracker + + d = {} + if self._static_deps: + d.update(self._static_deps) + # None is a placeholder for the current state class. + if None in d: + d[objclass.get_full_name()] = d.pop(None) + if not self._auto_deps: - return self._static_deps - d = self._static_deps.copy() + return d + if obj is None: fget = self._fget if fget is not None: obj = cast(FunctionType, fget) else: - return set() - with contextlib.suppress(AttributeError): - # unbox functools.partial - obj = cast(FunctionType, obj.func) # type: ignore - with contextlib.suppress(AttributeError): - # unbox EventHandler - obj = cast(FunctionType, obj.fn) # type: ignore + return d - if self_name is None and isinstance(obj, FunctionType): - try: - # the first argument to the function is the name of "self" arg - self_name = obj.__code__.co_varnames[0] - except (AttributeError, IndexError): - self_name = None - if self_name is None: - # cannot reference attributes on self if method takes no args - return set() + try: + return DependencyTracker( + func=obj, state_cls=objclass, dependencies=d + ).dependencies + except Exception as e: + console.warn( + "Failed to automatically determine dependencies for computed var " + f"{objclass.__name__}.{self._js_expr}: {e}. " + "Provide static_deps and set auto_deps=False to suppress this warning." + ) + return d - invalid_names = ["get_state", "parent_state", "substates", "get_substate"] - self_is_top_of_stack = False - for instruction in dis.get_instructions(obj): - if ( - instruction.opname in ("LOAD_FAST", "LOAD_DEREF") - and instruction.argval == self_name - ): - # bytecode loaded the class instance to the top of stack, next load instruction - # is referencing an attribute on self - self_is_top_of_stack = True - continue - if self_is_top_of_stack and instruction.opname in ( - "LOAD_ATTR", - "LOAD_METHOD", - ): - try: - ref_obj = getattr(objclass, instruction.argval) - except Exception: - ref_obj = None - if instruction.argval in invalid_names: - raise VarValueError( - f"Cached var {self!s} cannot access arbitrary state via `{instruction.argval}`." - ) - if callable(ref_obj): - # recurse into callable attributes - d.update( - self._deps( - objclass=objclass, - obj=ref_obj, - ) - ) - # recurse into property fget functions - elif isinstance(ref_obj, property) and not isinstance( - ref_obj, ComputedVar - ): - d.update( - self._deps( - objclass=objclass, - obj=ref_obj.fget, # type: ignore - ) - ) - elif ( - instruction.argval in objclass.backend_vars - or instruction.argval in objclass.vars - ): - # var access - d.add(instruction.argval) - elif instruction.opname == "LOAD_CONST" and isinstance( - instruction.argval, CodeType - ): - # recurse into nested functions / comprehensions, which can reference - # instance attributes from the outer scope - d.update( - self._deps( - objclass=objclass, - obj=instruction.argval, - self_name=self_name, - ) - ) - self_is_top_of_stack = False - return d - - def mark_dirty(self, instance) -> None: + def mark_dirty(self, instance: BaseState) -> None: """Mark this ComputedVar as dirty. Args: @@ -2209,6 +2323,37 @@ class ComputedVar(Var[RETURN_TYPE]): with contextlib.suppress(AttributeError): delattr(instance, self._cache_attr) + def add_dependency(self, objclass: Type[BaseState], dep: Var): + """Explicitly add a dependency to the ComputedVar. + + After adding the dependency, when the `dep` changes, this computed var + will be marked dirty. + + Args: + objclass: The class obj this ComputedVar is attached to. + dep: The dependency to add. + + Raises: + VarDependencyError: If the dependency is not a Var instance with a + state and field name + """ + if all_var_data := dep._get_all_var_data(): + state_name = all_var_data.state + if state_name: + var_name = all_var_data.field_name + if var_name: + self._static_deps.setdefault(state_name, set()).add(var_name) + objclass.get_root_state().get_class_substate( + state_name + )._var_dependencies.setdefault(var_name, set()).add( + (objclass.get_full_name(), self._js_expr) + ) + return + raise VarDependencyError( + "ComputedVar dependencies must be Var instances with a state and " + f"field name, got {dep!r}." + ) + def _determine_var_type(self) -> Type: """Get the type of the var. @@ -2218,7 +2363,7 @@ class ComputedVar(Var[RETURN_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: @@ -2245,6 +2390,126 @@ class DynamicRouteVar(ComputedVar[Union[str, List[str]]]): pass +async def _default_async_computed_var(_self: BaseState) -> Any: + return None + + +@dataclasses.dataclass( + eq=False, + frozen=True, + init=False, + slots=True, +) +class AsyncComputedVar(ComputedVar[RETURN_TYPE]): + """A computed var that wraps a coroutinefunction.""" + + _fget: Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]] = ( + dataclasses.field(default=_default_async_computed_var) + ) + + @overload + def __get__( + self: AsyncComputedVar[bool], + instance: None, + owner: Type, + ) -> BooleanVar: ... + + @overload + def __get__( + self: AsyncComputedVar[int] | ComputedVar[float], + instance: None, + owner: Type, + ) -> NumberVar: ... + + @overload + def __get__( + self: AsyncComputedVar[str], + instance: None, + owner: Type, + ) -> StringVar: ... + + @overload + def __get__( + self: AsyncComputedVar[Mapping[DICT_KEY, DICT_VAL]], + instance: None, + owner: Type, + ) -> ObjectVar[Mapping[DICT_KEY, DICT_VAL]]: ... + + @overload + def __get__( + self: AsyncComputedVar[list[LIST_INSIDE]], + instance: None, + owner: Type, + ) -> ArrayVar[list[LIST_INSIDE]]: ... + + @overload + def __get__( + self: AsyncComputedVar[tuple[LIST_INSIDE, ...]], + instance: None, + owner: Type, + ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ... + + @overload + def __get__(self, instance: None, owner: Type) -> AsyncComputedVar[RETURN_TYPE]: ... + + @overload + def __get__( + self, instance: BaseState, owner: Type + ) -> Coroutine[None, None, RETURN_TYPE]: ... + + def __get__( + self, instance: BaseState | None, owner + ) -> Var | Coroutine[None, None, RETURN_TYPE]: + """Get the ComputedVar value. + + If the value is already cached on the instance, return the cached value. + + Args: + instance: the instance of the class accessing this computed var. + owner: the class that this descriptor is attached to. + + Returns: + The value of the var for the given instance. + """ + if instance is None: + return super(AsyncComputedVar, self).__get__(instance, owner) + + if not self._cache: + + async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE: + value = await self.fget(instance) + self._check_deprecated_return_type(instance, value) + return value + + return _awaitable_result() + else: + # handle caching + async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE: + if not hasattr(instance, self._cache_attr) or self.needs_update( + instance + ): + # Set cache attr on state instance. + setattr(instance, self._cache_attr, await self.fget(instance)) + # Ensure the computed var gets serialized to redis. + instance._was_touched = True + # Set the last updated timestamp on the state instance. + setattr(instance, self._last_updated_attr, datetime.datetime.now()) + value = getattr(instance, self._cache_attr) + self._check_deprecated_return_type(instance, value) + return value + + return _awaitable_result() + + @property + def fget(self) -> Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]]: + """Get the getter function. + + Returns: + The getter function. + """ + return self._fget + + if TYPE_CHECKING: BASE_STATE = TypeVar("BASE_STATE", bound=BaseState) @@ -2259,7 +2524,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 @@ -2311,10 +2576,27 @@ def computed_var( raise VarDependencyError("Cannot track dependencies without caching.") if fget is not None: - return ComputedVar(fget, cache=cache) + if inspect.iscoroutinefunction(fget): + computed_var_cls = AsyncComputedVar + else: + computed_var_cls = ComputedVar + return computed_var_cls( + fget, + initial_value=initial_value, + cache=cache, + deps=deps, + auto_deps=auto_deps, + interval=interval, + backend=backend, + **kwargs, + ) def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar: - return ComputedVar( + if inspect.iscoroutinefunction(fget): + computed_var_cls = AsyncComputedVar + else: + computed_var_cls = ComputedVar + return computed_var_cls( fget, initial_value=initial_value, cache=cache, @@ -2383,7 +2665,7 @@ def var_operation_return( @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class CustomVarOperation(CachedVarOperation, Var[T]): """Base class for custom var operations.""" @@ -2454,7 +2736,7 @@ class NoneVar(Var[None], python_types=type(None)): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralNoneVar(LiteralVar, NoneVar): """A var representing None.""" @@ -2516,7 +2798,7 @@ def get_to_operation(var_subclass: Type[Var]) -> Type[ToOperation]: @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class StateOperation(CachedVarOperation, Var): """A var operation that accesses a field on an object.""" @@ -2588,7 +2870,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}, @@ -2648,7 +2930,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)) @@ -2659,23 +2941,10 @@ 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 -# These names were changed in reflex 0.3.0 -REPLACED_NAMES = { - "full_name": "_var_full_name", - "name": "_js_expr", - "state": "_var_data.state", - "type_": "_var_type", - "is_local": "_var_is_local", - "is_string": "_var_is_string", - "set_state": "_var_set_state", - "deps": "_deps", -} - - dispatchers: Dict[GenericType, Callable[[Var], Var]] = {} @@ -2756,7 +3025,7 @@ def generic_type_to_actual_type_map( # call recursively for nested generic types and merge the results return { k: v - for generic_arg, actual_arg in zip(generic_args, actual_args) + for generic_arg, actual_arg in zip(generic_args, actual_args, strict=True) for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items() } @@ -2915,11 +3184,14 @@ V = TypeVar("V") BASE_TYPE = TypeVar("BASE_TYPE", bound=Base) +FIELD_TYPE = TypeVar("FIELD_TYPE") +MAPPING_TYPE = TypeVar("MAPPING_TYPE", bound=Mapping) -class Field(Generic[T]): + +class Field(Generic[FIELD_TYPE]): """Shadow class for Var to allow for type hinting in the IDE.""" - def __set__(self, instance, value: T): + def __set__(self, instance: Any, value: FIELD_TYPE): """Set the Var. Args: @@ -2928,41 +3200,43 @@ class Field(Generic[T]): """ @overload - def __get__(self: Field[bool], instance: None, owner) -> BooleanVar: ... + def __get__(self: Field[bool], instance: None, owner: Any) -> BooleanVar: ... @overload - def __get__(self: Field[int], instance: None, owner) -> NumberVar: ... + def __get__( + self: Field[int] | Field[float] | Field[int | float], instance: None, owner: Any + ) -> NumberVar: ... @overload - def __get__(self: Field[str], instance: None, owner) -> StringVar: ... + def __get__(self: Field[str], instance: None, owner: Any) -> StringVar: ... @overload - def __get__(self: Field[None], instance: None, owner) -> NoneVar: ... + def __get__(self: Field[None], instance: None, owner: Any) -> NoneVar: ... @overload def __get__( self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]], instance: None, - owner, + owner: Any, ) -> ArrayVar[List[V]]: ... @overload def __get__( - self: Field[Dict[str, V]], instance: None, owner - ) -> ObjectVar[Dict[str, V]]: ... + self: Field[MAPPING_TYPE], instance: None, owner: Any + ) -> ObjectVar[MAPPING_TYPE]: ... @overload def __get__( - self: Field[BASE_TYPE], instance: None, owner + self: Field[BASE_TYPE], instance: None, owner: Any ) -> ObjectVar[BASE_TYPE]: ... @overload - def __get__(self, instance: None, owner) -> Var[T]: ... + def __get__(self, instance: None, owner: Any) -> Var[FIELD_TYPE]: ... @overload - def __get__(self, instance, owner) -> T: ... + def __get__(self, instance: Any, owner: Any) -> FIELD_TYPE: ... - def __get__(self, instance, owner): # type: ignore + def __get__(self, instance: Any, owner: Any): # pyright: ignore [reportInconsistentOverload] """Get the Var. Args: @@ -2971,7 +3245,7 @@ class Field(Generic[T]): """ -def field(value: T) -> Field[T]: +def field(value: FIELD_TYPE) -> Field[FIELD_TYPE]: """Create a Field with a value. Args: @@ -2980,4 +3254,4 @@ def field(value: T) -> Field[T]: 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 b6f4c24c6..a18df78d0 100644 --- a/reflex/vars/datetime.py +++ b/reflex/vars/datetime.py @@ -3,7 +3,6 @@ from __future__ import annotations import dataclasses -import sys from datetime import date, datetime from typing import Any, NoReturn, TypeVar, Union, overload @@ -40,7 +39,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 +58,7 @@ class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)): 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 +77,7 @@ class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)): 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 +96,7 @@ class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)): 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. @@ -185,7 +184,7 @@ def date_compare_operation( The result of the operation. """ return var_operation_return( - f"({lhs} { '<' if strict else '<='} {rhs})", + f"({lhs} {'<' if strict else '<='} {rhs})", bool, ) @@ -193,7 +192,7 @@ def date_compare_operation( @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralDatetimeVar(LiteralVar, DateTimeVar): """Base class for immutable datetime and date vars.""" diff --git a/reflex/vars/dep_tracking.py b/reflex/vars/dep_tracking.py new file mode 100644 index 000000000..0b2367799 --- /dev/null +++ b/reflex/vars/dep_tracking.py @@ -0,0 +1,344 @@ +"""Collection of base classes.""" + +from __future__ import annotations + +import contextlib +import dataclasses +import dis +import enum +import inspect +from types import CellType, CodeType, FunctionType +from typing import TYPE_CHECKING, Any, ClassVar, Type, cast + +from reflex.utils.exceptions import VarValueError + +if TYPE_CHECKING: + from reflex.state import BaseState + + from .base import Var + + +CellEmpty = object() + + +def get_cell_value(cell: CellType) -> Any: + """Get the value of a cell object. + + Args: + cell: The cell object to get the value from. (func.__closure__ objects) + + Returns: + The value from the cell or CellEmpty if a ValueError is raised. + """ + try: + return cell.cell_contents + except ValueError: + return CellEmpty + + +class ScanStatus(enum.Enum): + """State of the dis instruction scanning loop.""" + + SCANNING = enum.auto() + GETTING_ATTR = enum.auto() + GETTING_STATE = enum.auto() + GETTING_VAR = enum.auto() + + +@dataclasses.dataclass +class DependencyTracker: + """State machine for identifying state attributes that are accessed by a function.""" + + func: FunctionType | CodeType = dataclasses.field() + state_cls: Type[BaseState] = dataclasses.field() + + dependencies: dict[str, set[str]] = dataclasses.field(default_factory=dict) + + scan_status: ScanStatus = dataclasses.field(default=ScanStatus.SCANNING) + top_of_stack: str | None = dataclasses.field(default=None) + + tracked_locals: dict[str, Type[BaseState]] = dataclasses.field(default_factory=dict) + + _getting_state_class: Type[BaseState] | None = dataclasses.field(default=None) + _getting_var_instructions: list[dis.Instruction] = dataclasses.field( + default_factory=list + ) + + INVALID_NAMES: ClassVar[list[str]] = ["parent_state", "substates", "get_substate"] + + def __post_init__(self): + """After initializing, populate the dependencies dict.""" + with contextlib.suppress(AttributeError): + # unbox functools.partial + self.func = cast(FunctionType, self.func.func) # pyright: ignore[reportAttributeAccessIssue] + with contextlib.suppress(AttributeError): + # unbox EventHandler + self.func = cast(FunctionType, self.func.fn) # pyright: ignore[reportAttributeAccessIssue] + + if isinstance(self.func, FunctionType): + with contextlib.suppress(AttributeError, IndexError): + # the first argument to the function is the name of "self" arg + self.tracked_locals[self.func.__code__.co_varnames[0]] = self.state_cls + + self._populate_dependencies() + + def _merge_deps(self, tracker: DependencyTracker) -> None: + """Merge dependencies from another DependencyTracker. + + Args: + tracker: The DependencyTracker to merge dependencies from. + """ + for state_name, dep_name in tracker.dependencies.items(): + self.dependencies.setdefault(state_name, set()).update(dep_name) + + def load_attr_or_method(self, instruction: dis.Instruction) -> None: + """Handle loading an attribute or method from the object on top of the stack. + + This method directly tracks attributes and recursively merges + dependencies from analyzing the dependencies of any methods called. + + Args: + instruction: The dis instruction to process. + + Raises: + VarValueError: if the attribute is an disallowed name. + """ + from .base import ComputedVar + + if instruction.argval in self.INVALID_NAMES: + raise VarValueError( + f"Cached var {self!s} cannot access arbitrary state via `{instruction.argval}`." + ) + if instruction.argval == "get_state": + # Special case: arbitrary state access requested. + self.scan_status = ScanStatus.GETTING_STATE + return + if instruction.argval == "get_var_value": + # Special case: arbitrary var access requested. + self.scan_status = ScanStatus.GETTING_VAR + return + + # Reset status back to SCANNING after attribute is accessed. + self.scan_status = ScanStatus.SCANNING + if not self.top_of_stack: + return + target_state = self.tracked_locals[self.top_of_stack] + try: + ref_obj = getattr(target_state, instruction.argval) + except AttributeError: + # Not found on this state class, maybe it is a dynamic attribute that will be picked up later. + ref_obj = None + + if isinstance(ref_obj, property) and not isinstance(ref_obj, ComputedVar): + # recurse into property fget functions + ref_obj = ref_obj.fget + if callable(ref_obj): + # recurse into callable attributes + self._merge_deps( + type(self)(func=cast(FunctionType, ref_obj), state_cls=target_state) + ) + elif ( + instruction.argval in target_state.backend_vars + or instruction.argval in target_state.vars + ): + # var access + self.dependencies.setdefault(target_state.get_full_name(), set()).add( + instruction.argval + ) + + def _get_globals(self) -> dict[str, Any]: + """Get the globals of the function. + + Returns: + The var names and values in the globals of the function. + """ + if isinstance(self.func, CodeType): + return {} + return self.func.__globals__ # pyright: ignore[reportAttributeAccessIssue] + + def _get_closure(self) -> dict[str, Any]: + """Get the closure of the function, with unbound values omitted. + + Returns: + The var names and values in the closure of the function. + """ + if isinstance(self.func, CodeType): + return {} + return { + var_name: get_cell_value(cell) + for var_name, cell in zip( + self.func.__code__.co_freevars, # pyright: ignore[reportAttributeAccessIssue] + self.func.__closure__ or (), + strict=False, + ) + if get_cell_value(cell) is not CellEmpty + } + + def handle_getting_state(self, instruction: dis.Instruction) -> None: + """Handle bytecode analysis when `get_state` was called in the function. + + If the wrapped function is getting an arbitrary state and saving it to a + local variable, this method associates the local variable name with the + state class in self.tracked_locals. + + When an attribute/method is accessed on a tracked local, it will be + associated with this state. + + Args: + instruction: The dis instruction to process. + + Raises: + VarValueError: if the state class cannot be determined from the instruction. + """ + from reflex.state import BaseState + + if instruction.opname == "LOAD_FAST": + raise VarValueError( + f"Dependency detection cannot identify get_state class from local var {instruction.argval}." + ) + if isinstance(self.func, CodeType): + raise VarValueError( + "Dependency detection cannot identify get_state class from a code object." + ) + if instruction.opname == "LOAD_GLOBAL": + # Special case: referencing state class from global scope. + try: + self._getting_state_class = self._get_globals()[instruction.argval] + except (ValueError, KeyError) as ve: + raise VarValueError( + f"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, not found in globals." + ) from ve + elif instruction.opname == "LOAD_DEREF": + # Special case: referencing state class from closure. + try: + self._getting_state_class = self._get_closure()[instruction.argval] + except (ValueError, KeyError) as ve: + raise VarValueError( + f"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, is it defined yet?" + ) from ve + elif instruction.opname == "STORE_FAST": + # Storing the result of get_state in a local variable. + if not isinstance(self._getting_state_class, type) or not issubclass( + self._getting_state_class, BaseState + ): + raise VarValueError( + f"Cached var {self!s} cannot determine dependencies in fetched state `{instruction.argval}`." + ) + self.tracked_locals[instruction.argval] = self._getting_state_class + self.scan_status = ScanStatus.SCANNING + self._getting_state_class = None + + def _eval_var(self) -> Var: + """Evaluate instructions from the wrapped function to get the Var object. + + Returns: + The Var object. + + Raises: + VarValueError: if the source code for the var cannot be determined. + """ + # Get the original source code and eval it to get the Var. + module = inspect.getmodule(self.func) + positions0 = self._getting_var_instructions[0].positions + positions1 = self._getting_var_instructions[-1].positions + if module is None or positions0 is None or positions1 is None: + raise VarValueError( + f"Cannot determine the source code for the var in {self.func!r}." + ) + start_line = positions0.lineno + start_column = positions0.col_offset + end_line = positions1.end_lineno + end_column = positions1.end_col_offset + if ( + start_line is None + or start_column is None + or end_line is None + or end_column is None + ): + raise VarValueError( + f"Cannot determine the source code for the var in {self.func!r}." + ) + source = inspect.getsource(module).splitlines(True)[start_line - 1 : end_line] + # Create a python source string snippet. + if len(source) > 1: + snipped_source = "".join( + [ + *source[0][start_column:], + *(source[1:-2] if len(source) > 2 else []), + *source[-1][: end_column - 1], + ] + ) + else: + snipped_source = source[0][start_column : end_column - 1] + # Evaluate the string in the context of the function's globals and closure. + return eval(f"({snipped_source})", self._get_globals(), self._get_closure()) + + def handle_getting_var(self, instruction: dis.Instruction) -> None: + """Handle bytecode analysis when `get_var_value` was called in the function. + + This only really works if the expression passed to `get_var_value` is + evaluable in the function's global scope or closure, so getting the var + value from a var saved in a local variable or in the class instance is + not possible. + + Args: + instruction: The dis instruction to process. + + Raises: + VarValueError: if the source code for the var cannot be determined. + """ + if instruction.opname == "CALL" and self._getting_var_instructions: + if self._getting_var_instructions: + the_var = self._eval_var() + the_var_data = the_var._get_all_var_data() + if the_var_data is None: + raise VarValueError( + f"Cannot determine the source code for the var in {self.func!r}." + ) + self.dependencies.setdefault(the_var_data.state, set()).add( + the_var_data.field_name + ) + self._getting_var_instructions.clear() + self.scan_status = ScanStatus.SCANNING + else: + self._getting_var_instructions.append(instruction) + + def _populate_dependencies(self) -> None: + """Update self.dependencies based on the disassembly of self.func. + + Save references to attributes accessed on "self" or other fetched states. + + Recursively called when the function makes a method call on "self" or + define comprehensions or nested functions that may reference "self". + """ + for instruction in dis.get_instructions(self.func): + if self.scan_status == ScanStatus.GETTING_STATE: + self.handle_getting_state(instruction) + elif self.scan_status == ScanStatus.GETTING_VAR: + self.handle_getting_var(instruction) + elif ( + instruction.opname in ("LOAD_FAST", "LOAD_DEREF") + and instruction.argval in self.tracked_locals + ): + # bytecode loaded the class instance to the top of stack, next load instruction + # is referencing an attribute on self + self.top_of_stack = instruction.argval + self.scan_status = ScanStatus.GETTING_ATTR + elif self.scan_status == ScanStatus.GETTING_ATTR and instruction.opname in ( + "LOAD_ATTR", + "LOAD_METHOD", + ): + self.load_attr_or_method(instruction) + self.top_of_stack = None + elif instruction.opname == "LOAD_CONST" and isinstance( + instruction.argval, CodeType + ): + # recurse into nested functions / comprehensions, which can reference + # instance attributes from the outer scope + self._merge_deps( + type(self)( + func=instruction.argval, + state_cls=self.state_cls, + tracked_locals=self.tracked_locals, + ) + ) diff --git a/reflex/vars/function.py b/reflex/vars/function.py index 131f15b9f..505a69b4c 100644 --- a/reflex/vars/function.py +++ b/reflex/vars/function.py @@ -100,7 +100,7 @@ class FunctionVar(Var[CALLABLE_TYPE], default_type=ReflexCallable[Any, Any]): @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 @@ class FunctionVar(Var[CALLABLE_TYPE], default_type=ReflexCallable[Any, Any]): @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: @@ -210,6 +210,7 @@ class FunctionStringVar(FunctionVar[CALLABLE_TYPE]): Args: func: The function to call. + _var_type: The type of the Var. _var_data: Additional hooks and imports associated with the Var. Returns: @@ -225,7 +226,7 @@ class FunctionStringVar(FunctionVar[CALLABLE_TYPE]): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]): """Base class for immutable vars that are the result of a function call.""" @@ -268,6 +269,7 @@ class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]): Args: func: The function to call. *args: The arguments to call the function with. + _var_type: The type of the Var. _var_data: Additional hooks and imports associated with the Var. Returns: @@ -348,7 +350,7 @@ def format_args_function_operation( @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ArgsFunctionOperation(CachedVarOperation, FunctionVar): """Base class for immutable function defined via arguments and return expression.""" @@ -385,6 +387,7 @@ class ArgsFunctionOperation(CachedVarOperation, FunctionVar): return_expr: The return expression of the function. rest: The name of the rest argument. explicit_return: Whether to use explicit return syntax. + _var_type: The type of the Var. _var_data: Additional hooks and imports associated with the Var. Returns: @@ -404,7 +407,7 @@ class ArgsFunctionOperation(CachedVarOperation, FunctionVar): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ArgsFunctionOperationBuilder(CachedVarOperation, BuilderFunctionVar): """Base class for immutable function defined via arguments and return expression with the builder pattern.""" @@ -441,6 +444,7 @@ class ArgsFunctionOperationBuilder(CachedVarOperation, BuilderFunctionVar): return_expr: The return expression of the function. rest: The name of the rest argument. explicit_return: Whether to use explicit return syntax. + _var_type: The type of the Var. _var_data: Additional hooks and imports associated with the Var. Returns: diff --git a/reflex/vars/number.py b/reflex/vars/number.py index a2a0293d5..35a55490a 100644 --- a/reflex/vars/number.py +++ b/reflex/vars/number.py @@ -5,7 +5,6 @@ from __future__ import annotations import dataclasses import json import math -import sys from typing import ( TYPE_CHECKING, Any, @@ -18,7 +17,7 @@ from typing import ( ) from reflex.constants.base import Dirs -from reflex.utils.exceptions import PrimitiveUnserializableToJSON, VarTypeError +from reflex.utils.exceptions import PrimitiveUnserializableToJSONError, VarTypeError from reflex.utils.imports import ImportDict, ImportVar from .base import ( @@ -31,7 +30,7 @@ from .base import ( var_operation_return, ) -NUMBER_T = TypeVar("NUMBER_T", int, float, Union[int, float], bool) +NUMBER_T = TypeVar("NUMBER_T", int, float, bool) if TYPE_CHECKING: from .sequence import ArrayVar @@ -61,7 +60,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 +79,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +98,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +118,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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. @@ -160,7 +159,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): """ from .sequence import ArrayVar, LiteralArrayVar - if isinstance(other, (list, tuple, set, ArrayVar)): + if isinstance(other, (list, tuple, ArrayVar)): if isinstance(other, ArrayVar): return other * self return LiteralArrayVar.create(other) * self @@ -187,7 +186,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): """ from .sequence import ArrayVar, LiteralArrayVar - if isinstance(other, (list, tuple, set, ArrayVar)): + if isinstance(other, (list, tuple, ArrayVar)): if isinstance(other, ArrayVar): return other * self return LiteralArrayVar.create(other) * self @@ -201,7 +200,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +220,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +240,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +260,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +280,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +300,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +320,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +340,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +416,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +435,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +480,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +499,7 @@ class NumberVar(Var[NUMBER_T], python_types=(int, float)): 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 +560,7 @@ def binary_number_operation( Returns: The binary number operation. """ - return operation(lhs, rhs) # type: ignore + return operation(lhs, rhs) # pyright: ignore [reportReturnType, reportArgumentType] return wrapper @@ -973,7 +972,7 @@ def boolean_not_operation(value: BooleanVar): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralNumberVar(LiteralVar, NumberVar): """Base class for immutable literal number vars.""" @@ -987,10 +986,10 @@ class LiteralNumberVar(LiteralVar, NumberVar): The JSON representation of the var. Raises: - PrimitiveUnserializableToJSON: If the var is unserializable to JSON. + PrimitiveUnserializableToJSONError: If the var is unserializable to JSON. """ if math.isinf(self._var_value) or math.isnan(self._var_value): - raise PrimitiveUnserializableToJSON( + raise PrimitiveUnserializableToJSONError( f"No valid JSON representation for {self}" ) return json.dumps(self._var_value) @@ -1032,7 +1031,7 @@ class LiteralNumberVar(LiteralVar, NumberVar): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralBooleanVar(LiteralVar, BooleanVar): """Base class for immutable literal boolean vars.""" diff --git a/reflex/vars/object.py b/reflex/vars/object.py index 5de431f5a..cb29cabfb 100644 --- a/reflex/vars/object.py +++ b/reflex/vars/object.py @@ -3,13 +3,12 @@ from __future__ import annotations import dataclasses -import sys import typing from inspect import isclass from typing import ( Any, - Dict, List, + Mapping, NoReturn, Tuple, Type, @@ -19,6 +18,8 @@ from typing import ( overload, ) +from typing_extensions import is_typeddict + from reflex.utils import types from reflex.utils.exceptions import VarAttributeError from reflex.utils.types import GenericType, get_attribute_access_type, get_origin @@ -36,7 +37,7 @@ from .base import ( from .number import BooleanVar, NumberVar, raise_unsupported_operand_types from .sequence import ArrayVar, StringVar -OBJECT_TYPE = TypeVar("OBJECT_TYPE") +OBJECT_TYPE = TypeVar("OBJECT_TYPE", covariant=True) KEY_TYPE = TypeVar("KEY_TYPE") VALUE_TYPE = TypeVar("VALUE_TYPE") @@ -46,7 +47,7 @@ ARRAY_INNER_TYPE = TypeVar("ARRAY_INNER_TYPE") OTHER_KEY_TYPE = TypeVar("OTHER_KEY_TYPE") -class ObjectVar(Var[OBJECT_TYPE], python_types=dict): +class ObjectVar(Var[OBJECT_TYPE], python_types=Mapping): """Base class for immutable object vars.""" def _key_type(self) -> Type: @@ -59,7 +60,7 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): @overload def _value_type( - self: ObjectVar[Dict[Any, VALUE_TYPE]], + self: ObjectVar[Mapping[Any, VALUE_TYPE]], ) -> Type[VALUE_TYPE]: ... @overload @@ -73,9 +74,9 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): """ fixed_type = get_origin(self._var_type) or self._var_type if not isclass(fixed_type): - return Any - args = get_args(self._var_type) if issubclass(fixed_type, dict) else () - return args[1] if args else 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 # pyright: ignore [reportReturnType] def keys(self) -> ArrayVar[List[str]]: """Get the keys of the object. @@ -87,7 +88,7 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): @overload def values( - self: ObjectVar[Dict[Any, VALUE_TYPE]], + self: ObjectVar[Mapping[Any, VALUE_TYPE]], ) -> ArrayVar[List[VALUE_TYPE]]: ... @overload @@ -103,7 +104,7 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): @overload def entries( - self: ObjectVar[Dict[Any, VALUE_TYPE]], + self: ObjectVar[Mapping[Any, VALUE_TYPE]], ) -> ArrayVar[List[Tuple[str, VALUE_TYPE]]]: ... @overload @@ -132,50 +133,50 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): # NoReturn is used here to catch when key value is Any @overload - def __getitem__( - self: ObjectVar[Dict[Any, NoReturn]], + def __getitem__( # pyright: ignore [reportOverlappingOverload] + self: ObjectVar[Mapping[Any, NoReturn]], key: Var | Any, ) -> Var: ... + @overload + def __getitem__( + self: (ObjectVar[Mapping[Any, bool]]), + key: Var | Any, + ) -> BooleanVar: ... + @overload def __getitem__( self: ( - ObjectVar[Dict[Any, int]] - | ObjectVar[Dict[Any, float]] - | ObjectVar[Dict[Any, int | float]] + ObjectVar[Mapping[Any, int]] + | ObjectVar[Mapping[Any, float]] + | ObjectVar[Mapping[Any, int | float]] ), key: Var | Any, ) -> NumberVar: ... @overload def __getitem__( - self: ObjectVar[Dict[Any, str]], + self: ObjectVar[Mapping[Any, str]], key: Var | Any, ) -> StringVar: ... @overload def __getitem__( - self: ObjectVar[Dict[Any, list[ARRAY_INNER_TYPE]]], + self: ObjectVar[Mapping[Any, list[ARRAY_INNER_TYPE]]], key: Var | Any, ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ... @overload def __getitem__( - self: ObjectVar[Dict[Any, set[ARRAY_INNER_TYPE]]], - key: Var | Any, - ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ... - - @overload - def __getitem__( - self: ObjectVar[Dict[Any, tuple[ARRAY_INNER_TYPE, ...]]], + self: ObjectVar[Mapping[Any, tuple[ARRAY_INNER_TYPE, ...]]], key: Var | Any, ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ... @overload def __getitem__( - self: ObjectVar[Dict[Any, dict[OTHER_KEY_TYPE, VALUE_TYPE]]], + self: ObjectVar[Mapping[Any, Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]], key: Var | Any, - ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ... + ) -> ObjectVar[Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]: ... def __getitem__(self, key: Var | Any) -> Var: """Get an item from the object. @@ -194,50 +195,44 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): # NoReturn is used here to catch when key value is Any @overload - def __getattr__( - self: ObjectVar[Dict[Any, NoReturn]], + def __getattr__( # pyright: ignore [reportOverlappingOverload] + self: ObjectVar[Mapping[Any, NoReturn]], name: str, ) -> Var: ... @overload def __getattr__( self: ( - ObjectVar[Dict[Any, int]] - | ObjectVar[Dict[Any, float]] - | ObjectVar[Dict[Any, int | float]] + ObjectVar[Mapping[Any, int]] + | ObjectVar[Mapping[Any, float]] + | ObjectVar[Mapping[Any, int | float]] ), name: str, ) -> NumberVar: ... @overload def __getattr__( - self: ObjectVar[Dict[Any, str]], + self: ObjectVar[Mapping[Any, str]], name: str, ) -> StringVar: ... @overload def __getattr__( - self: ObjectVar[Dict[Any, list[ARRAY_INNER_TYPE]]], + self: ObjectVar[Mapping[Any, list[ARRAY_INNER_TYPE]]], name: str, ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ... @overload def __getattr__( - self: ObjectVar[Dict[Any, set[ARRAY_INNER_TYPE]]], - name: str, - ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ... - - @overload - def __getattr__( - self: ObjectVar[Dict[Any, tuple[ARRAY_INNER_TYPE, ...]]], + self: ObjectVar[Mapping[Any, tuple[ARRAY_INNER_TYPE, ...]]], name: str, ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ... @overload def __getattr__( - self: ObjectVar[Dict[Any, dict[OTHER_KEY_TYPE, VALUE_TYPE]]], + self: ObjectVar[Mapping[Any, Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]], name: str, - ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ... + ) -> ObjectVar[Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]: ... @overload def __getattr__( @@ -245,7 +240,7 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): name: str, ) -> ObjectItemOperation: ... - def __getattr__(self, name) -> Var: + def __getattr__(self, name: str) -> Var: """Get an attribute of the var. Args: @@ -266,8 +261,11 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): var_type = get_args(var_type)[0] fixed_type = var_type if isclass(var_type) else get_origin(var_type) - if (isclass(fixed_type) and not issubclass(fixed_type, dict)) or ( - fixed_type in types.UnionTypes + + if ( + (isclass(fixed_type) and not issubclass(fixed_type, Mapping)) + or (fixed_type in types.UnionTypes) + or is_typeddict(fixed_type) ): attribute_type = get_attribute_access_type(var_type, name) if attribute_type is None: @@ -294,12 +292,12 @@ class ObjectVar(Var[OBJECT_TYPE], python_types=dict): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar): """Base class for immutable literal object vars.""" - _var_value: Dict[Union[Var, Any], Union[Var, Any]] = dataclasses.field( + _var_value: Mapping[Union[Var, Any], Union[Var, Any]] = dataclasses.field( default_factory=dict ) @@ -310,7 +308,7 @@ class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar): 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. @@ -319,7 +317,7 @@ class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar): 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: @@ -344,17 +342,20 @@ class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar): Returns: The JSON representation of the object. + + Raises: + TypeError: The keys and values of the object must be literal vars to get the JSON representation """ - return ( - "{" - + ", ".join( - [ - f"{LiteralVar.create(key).json()}:{LiteralVar.create(value).json()}" - for key, value in self._var_value.items() - ] - ) - + "}" - ) + keys_and_values = [] + for key, value in self._var_value.items(): + key = LiteralVar.create(key) + value = LiteralVar.create(value) + if not isinstance(key, LiteralVar) or not isinstance(value, LiteralVar): + raise TypeError( + "The keys and values of the object must be literal vars to get the JSON representation." + ) + keys_and_values.append(f"{key.json()}:{value.json()}") + return "{" + ", ".join(keys_and_values) + "}" def __hash__(self) -> int: """Get the hash of the var. @@ -383,7 +384,7 @@ class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar): @classmethod def create( cls, - _var_value: dict, + _var_value: Mapping, _var_type: Type[OBJECT_TYPE] | None = None, _var_data: VarData | None = None, ) -> LiteralObjectVar[OBJECT_TYPE]: @@ -466,7 +467,7 @@ def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar): """ return var_operation_return( js_expression=f"({{...{lhs}, ...{rhs}}})", - var_type=Dict[ + var_type=Mapping[ Union[lhs._key_type(), rhs._key_type()], Union[lhs._value_type(), rhs._value_type()], ], @@ -476,7 +477,7 @@ def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ObjectItemOperation(CachedVarOperation, Var): """Operation to get an item from an object.""" diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py index 5864e70b9..dfd9a6af8 100644 --- a/reflex/vars/sequence.py +++ b/reflex/vars/sequence.py @@ -6,7 +6,6 @@ import dataclasses import inspect import json import re -import sys import typing from typing import ( TYPE_CHECKING, @@ -15,7 +14,7 @@ from typing import ( List, Literal, NoReturn, - Set, + Sequence, Tuple, Type, Union, @@ -66,7 +65,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 +85,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +105,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +125,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +210,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): ) -> BooleanVar: ... @overload - def contains( + def contains( # pyright: ignore [reportOverlappingOverload] self, other: NoReturn, field: StringVar | str | None = None ) -> NoReturn: ... @@ -237,7 +236,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +255,7 @@ class StringVar(Var[STRING_TYPE], python_types=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 +274,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +293,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +313,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +333,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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 +353,7 @@ class StringVar(Var[STRING_TYPE], python_types=str): 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. @@ -596,7 +595,7 @@ _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL) @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralStringVar(LiteralVar, StringVar[str]): """Base class for immutable literal string vars.""" @@ -718,7 +717,7 @@ class LiteralStringVar(LiteralVar, StringVar[str]): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ConcatVarOperation(CachedVarOperation, StringVar[str]): """Representing a concatenation of literal string vars.""" @@ -780,7 +779,7 @@ class ConcatVarOperation(CachedVarOperation, StringVar[str]): """Create a var from a string value. Args: - value: The values to concatenate. + *value: The values to concatenate. _var_data: Additional hooks and imports associated with the Var. Returns: @@ -794,7 +793,8 @@ class ConcatVarOperation(CachedVarOperation, StringVar[str]): ) -ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Union[List, Tuple, Set]) +ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Sequence, covariant=True) +OTHER_ARRAY_VAR_TYPE = TypeVar("OTHER_ARRAY_VAR_TYPE", bound=Sequence) OTHER_TUPLE = TypeVar("OTHER_TUPLE") @@ -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 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): 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. @@ -887,6 +887,11 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): i: Literal[0, -2], ) -> NumberVar: ... + @overload + def __getitem__( + self: ArrayVar[Tuple[Any, bool]], i: Literal[1, -1] + ) -> BooleanVar: ... + @overload def __getitem__( self: ( @@ -914,7 +919,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): @overload def __getitem__( - self: ArrayVar[Tuple[Any, bool]], i: Literal[1, -1] + self: ARRAY_VAR_OF_LIST_ELEMENT[bool], i: int | NumberVar ) -> BooleanVar: ... @overload @@ -932,23 +937,12 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): self: ARRAY_VAR_OF_LIST_ELEMENT[str], i: int | NumberVar ) -> StringVar: ... - @overload - def __getitem__( - self: ARRAY_VAR_OF_LIST_ELEMENT[bool], i: int | NumberVar - ) -> BooleanVar: ... - @overload def __getitem__( self: ARRAY_VAR_OF_LIST_ELEMENT[List[INNER_ARRAY_VAR]], i: int | NumberVar, ) -> ArrayVar[List[INNER_ARRAY_VAR]]: ... - @overload - def __getitem__( - self: ARRAY_VAR_OF_LIST_ELEMENT[Set[INNER_ARRAY_VAR]], - i: int | NumberVar, - ) -> ArrayVar[Set[INNER_ARRAY_VAR]]: ... - @overload def __getitem__( self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[KEY_TYPE, VALUE_TYPE]], @@ -987,7 +981,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): raise_unsupported_operand_types("[]", (type(self), type(i))) return array_item_operation(self, i) - def length(self) -> NumberVar: + def length(self) -> NumberVar[int]: """Get the length of the array. Returns: @@ -1089,7 +1083,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): 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 +1101,7 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): return repeat_array_operation(self, other) - __rmul__ = __mul__ # type: ignore + __rmul__ = __mul__ @overload def __lt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ... @@ -1239,26 +1233,18 @@ class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)): LIST_ELEMENT = TypeVar("LIST_ELEMENT") -ARRAY_VAR_OF_LIST_ELEMENT = Union[ - ArrayVar[List[LIST_ELEMENT]], - ArrayVar[Set[LIST_ELEMENT]], - ArrayVar[Tuple[LIST_ELEMENT, ...]], -] +ARRAY_VAR_OF_LIST_ELEMENT = ArrayVar[Sequence[LIST_ELEMENT]] @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]): """Base class for immutable literal array vars.""" - _var_value: Union[ - List[Union[Var, Any]], - Set[Union[Var, Any]], - Tuple[Union[Var, Any], ...], - ] = dataclasses.field(default_factory=list) + _var_value: Sequence[Union[Var, Any]] = dataclasses.field(default=()) @cached_property_no_lock def _cached_var_name(self) -> str: @@ -1303,32 +1289,39 @@ class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]): Returns: The JSON representation of the var. + + Raises: + TypeError: If the array elements are not of type LiteralVar. """ - return ( - "[" - + ", ".join( - [LiteralVar.create(element).json() for element in self._var_value] - ) - + "]" - ) + elements = [] + for element in self._var_value: + element_var = LiteralVar.create(element) + if not isinstance(element_var, LiteralVar): + raise TypeError( + f"Array elements must be of type LiteralVar, not {type(element_var)}" + ) + elements.append(element_var.json()) + + return "[" + ", ".join(elements) + "]" @classmethod def create( cls, - value: ARRAY_VAR_TYPE, - _var_type: Type[ARRAY_VAR_TYPE] | None = None, + value: OTHER_ARRAY_VAR_TYPE, + _var_type: Type[OTHER_ARRAY_VAR_TYPE] | None = None, _var_data: VarData | None = None, - ) -> LiteralArrayVar[ARRAY_VAR_TYPE]: + ) -> LiteralArrayVar[OTHER_ARRAY_VAR_TYPE]: """Create a var from a string value. Args: value: The value to create the var from. + _var_type: The type of the var. _var_data: Additional hooks and imports associated with the Var. Returns: The var. """ - return cls( + return LiteralArrayVar( _js_expr="", _var_type=figure_out_type(value) if _var_type is None else _var_type, _var_data=_var_data, @@ -1355,7 +1348,7 @@ def string_split_operation(string: StringVar[Any], sep: StringVar | str = ""): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class ArraySliceOperation(CachedVarOperation, ArrayVar): """Base class for immutable string vars that are the result of a string slice operation.""" @@ -1592,7 +1585,7 @@ def array_range_operation( The range of numbers. """ return var_operation_return( - js_expression=f"Array.from({{ length: ({stop!s} - {start!s}) / {step!s} }}, (_, i) => {start!s} + i * {step!s})", + js_expression=f"Array.from({{ length: Math.ceil(({stop!s} - {start!s}) / {step!s}) }}, (_, i) => {start!s} + i * {step!s})", var_type=List[int], ) @@ -1618,7 +1611,9 @@ def array_contains_field_operation( @var_operation -def array_contains_operation(haystack: ArrayVar, needle: Any | Var): +def array_contains_operation( + haystack: ArrayVar, needle: Any | Var +) -> CustomVarOperationReturn[bool]: """Check if an array contains an element. Args: @@ -1661,7 +1656,7 @@ if TYPE_CHECKING: def map_array_operation( array: ArrayVar[ARRAY_VAR_TYPE], function: FunctionVar, -): +) -> CustomVarOperationReturn[List[Any]]: """Map a function over an array. Args: @@ -1691,7 +1686,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] ) @@ -1702,7 +1697,7 @@ class ColorVar(StringVar[Color], python_types=Color): @dataclasses.dataclass( eq=False, frozen=True, - **{"slots": True} if sys.version_info >= (3, 10) else {}, + slots=True, ) class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar): """Base class for immutable literal color vars.""" diff --git a/scripts/bun_install.sh b/scripts/bun_install.sh index 08a0817f6..6961544ad 100644 --- a/scripts/bun_install.sh +++ b/scripts/bun_install.sh @@ -78,6 +78,14 @@ case $platform in ;; esac +case "$target" in +'linux'*) + if [ -f /etc/alpine-release ]; then + target="$target-musl" + fi + ;; +esac + if [[ $target = darwin-x64 ]]; then # Is this process running in Rosetta? # redirect stderr to devnull to avoid error message when not running in Rosetta @@ -91,19 +99,20 @@ GITHUB=${GITHUB-"https://github.com"} github_repo="$GITHUB/oven-sh/bun" -if [[ $target = darwin-x64 ]]; then - # If AVX2 isn't supported, use the -baseline build +# If AVX2 isn't supported, use the -baseline build +case "$target" in +'darwin-x64'*) if [[ $(sysctl -a | grep machdep.cpu | grep AVX2) == '' ]]; then - target=darwin-x64-baseline + target="$target-baseline" fi -fi - -if [[ $target = linux-x64 ]]; then + ;; +'linux-x64'*) # If AVX2 isn't supported, use the -baseline build if [[ $(cat /proc/cpuinfo | grep avx2) = '' ]]; then - target=linux-x64-baseline + target="$target-baseline" fi -fi + ;; +esac exe_name=bun @@ -113,8 +122,10 @@ if [[ $# = 2 && $2 = debug-info ]]; then info "You requested a debug build of bun. More information will be shown if a crash occurs." fi +bun_version=BUN_VERSION + if [[ $# = 0 ]]; then - bun_uri=$github_repo/releases/latest/download/bun-$target.zip + bun_uri=$github_repo/releases/download/bun-v$bun_version/bun-$target.zip else bun_uri=$github_repo/releases/download/$1/bun-$target.zip fi diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 3c432ac3b..52f1bcc14 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -214,8 +214,12 @@ function Install-Bun { # http://community.sqlbackupandftp.com/t/error-1073741515-solved/1305 if (($LASTEXITCODE -eq 3221225781) -or ($LASTEXITCODE -eq -1073741515)) # STATUS_DLL_NOT_FOUND { + # TODO: as of July 2024, Bun has no external dependencies. + # I want to keep this error message in for a few months to ensure that + # if someone somehow runs into this, it can be reported. Write-Output "Install Failed - You are missing a DLL required to run bun.exe" Write-Output "This can be solved by installing the Visual C++ Redistributable from Microsoft:`nSee https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist`nDirect Download -> https://aka.ms/vs/17/release/vc_redist.x64.exe`n`n" + Write-Output "The error above should be unreachable as Bun does not depend on this library. Please comment in https://github.com/oven-sh/bun/issues/8598 or open a new issue.`n`n" Write-Output "The command '${BunBin}\bun.exe --revision' exited with code ${LASTEXITCODE}`n" return 1 } diff --git a/scripts/wait_for_listening_port.py b/scripts/wait_for_listening_port.py index 43581f0bc..4befa00bd 100644 --- a/scripts/wait_for_listening_port.py +++ b/scripts/wait_for_listening_port.py @@ -14,7 +14,7 @@ from typing import Tuple import psutil -def _pid_exists(pid): +def _pid_exists(pid: int): # os.kill(pid, 0) doesn't work on Windows (actually kills the PID) # psutil.pid_exists() doesn't work on Windows (does os.kill underneath) # psutil.pids() seems to return the right thing. Inefficient but doesn't matter - keeps things simple. @@ -23,7 +23,7 @@ def _pid_exists(pid): return pid in psutil.pids() -def _wait_for_port(port, server_pid, timeout) -> Tuple[bool, str]: +def _wait_for_port(port: int, server_pid: int, timeout: float) -> Tuple[bool, str]: start = time.time() print(f"Waiting for up to {timeout} seconds for port {port} to start listening.") # noqa: T201 while True: diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index d11344903..67bd26c49 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,8 +1,6 @@ """Shared conftest for all integration tests.""" import os -import re -from pathlib import Path import pytest @@ -36,34 +34,6 @@ def xvfb(): yield None -def pytest_exception_interact(node, call, report): - """Take and upload screenshot when tests fail. - - Args: - node: The pytest item that failed. - call: The pytest call describing when/where the test was invoked. - report: The pytest log report object. - """ - screenshot_dir = environment.SCREENSHOT_DIR.get() - if DISPLAY is None or screenshot_dir is None: - return - - screenshot_dir = Path(screenshot_dir) - screenshot_dir.mkdir(parents=True, exist_ok=True) - safe_filename = re.sub( - r"(?u)[^-\w.]", - "_", - str(node.nodeid).strip().replace(" ", "_").replace(":", "_").replace(".py", ""), - ) - - try: - DISPLAY.waitgrab().save( - (Path(screenshot_dir) / safe_filename).with_suffix(".png"), - ) - except Exception as e: - print(f"Failed to take screenshot for {node}: {e}") - - @pytest.fixture( scope="session", params=[AppHarness, AppHarnessProd], ids=["dev", "prod"] ) diff --git a/tests/integration/init-test/Dockerfile b/tests/integration/init-test/Dockerfile index f30466e7f..e5d2a0820 100644 --- a/tests/integration/init-test/Dockerfile +++ b/tests/integration/init-test/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.9 +FROM python:3.10 ARG USERNAME=kerrigan RUN useradd -m $USERNAME diff --git a/tests/integration/test_background_task.py b/tests/integration/test_background_task.py index d7fe20824..f312f8122 100644 --- a/tests/integration/test_background_task.py +++ b/tests/integration/test_background_task.py @@ -37,9 +37,9 @@ def BackgroundTask(): 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 BackgroundTask(): 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", @@ -172,7 +172,7 @@ def BackgroundTask(): rx.button("Reset", on_click=State.reset_counter, id="reset"), ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) @@ -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_call_script.py b/tests/integration/test_call_script.py index 203c20e9b..f57dd2850 100644 --- a/tests/integration/test_call_script.py +++ b/tests/integration/test_call_script.py @@ -16,7 +16,7 @@ from .utils import SessionStorage def CallScript(): """A test app for browser javascript integration.""" from pathlib import Path - from typing import Dict, List, Optional, Union + from typing import Optional, Union import reflex as rx @@ -43,15 +43,17 @@ def CallScript(): external_scripts = inline_scripts.replace("inline", "external") class CallScriptState(rx.State): - results: List[Optional[Union[str, Dict, List]]] = [] - inline_counter: int = 0 - external_counter: int = 0 + results: rx.Field[list[Optional[Union[str, dict, list]]]] = rx.field([]) + inline_counter: rx.Field[int] = rx.field(0) + external_counter: rx.Field[int] = rx.field(0) value: str = "Initial" - last_result: str = "" + last_result: int = 0 + @rx.event def call_script_callback(self, result): self.results.append(result) + @rx.event def call_script_callback_other_arg(self, result, other_arg): self.results.append([other_arg, result]) @@ -91,7 +93,7 @@ def CallScript(): def call_script_inline_return_lambda(self): return rx.call_script( "inline2()", - callback=lambda result: CallScriptState.call_script_callback_other_arg( # type: ignore + callback=lambda result: CallScriptState.call_script_callback_other_arg( result, "lambda" ), ) @@ -100,7 +102,7 @@ def CallScript(): def get_inline_counter(self): return rx.call_script( "inline_counter", - callback=CallScriptState.set_inline_counter, # type: ignore + callback=CallScriptState.setvar("inline_counter"), ) @rx.event @@ -139,7 +141,7 @@ def CallScript(): def call_script_external_return_lambda(self): return rx.call_script( "external2()", - callback=lambda result: CallScriptState.call_script_callback_other_arg( # type: ignore + callback=lambda result: CallScriptState.call_script_callback_other_arg( result, "lambda" ), ) @@ -148,28 +150,28 @@ def CallScript(): def get_external_counter(self): return rx.call_script( "external_counter", - callback=CallScriptState.set_external_counter, # type: ignore + callback=CallScriptState.setvar("external_counter"), ) @rx.event def call_with_var_f_string(self): return rx.call_script( f"{rx.Var('inline_counter')} + {rx.Var('external_counter')}", - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ) @rx.event def call_with_var_str_cast(self): return rx.call_script( f"{rx.Var('inline_counter')!s} + {rx.Var('external_counter')!s}", - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ) @rx.event def call_with_var_f_string_wrapped(self): return rx.call_script( rx.Var(f"{rx.Var('inline_counter')} + {rx.Var('external_counter')}"), - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ) @rx.event @@ -178,7 +180,7 @@ def CallScript(): rx.Var( f"{rx.Var('inline_counter')!s} + {rx.Var('external_counter')!s}" ), - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ) @rx.event @@ -186,24 +188,24 @@ def CallScript(): yield rx.call_script("inline_counter = 0; external_counter = 0") self.reset() - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) Path("assets/external.js").write_text(external_scripts) @app.add_page def index(): return rx.vstack( rx.input( - value=CallScriptState.inline_counter.to(str), # type: ignore + value=CallScriptState.inline_counter.to(str), id="inline_counter", read_only=True, ), rx.input( - value=CallScriptState.external_counter.to(str), # type: ignore + value=CallScriptState.external_counter.to(str), id="external_counter", read_only=True, ), rx.text_area( - value=CallScriptState.results.to_string(), # type: ignore + value=CallScriptState.results.to_string(), id="results", read_only=True, ), @@ -273,7 +275,7 @@ def CallScript(): CallScriptState.value, on_click=rx.call_script( "'updated'", - callback=CallScriptState.set_value, # type: ignore + callback=CallScriptState.setvar("value"), ), id="update_value", ), @@ -282,7 +284,7 @@ def CallScript(): value=CallScriptState.last_result, id="last_result", read_only=True, - on_click=CallScriptState.set_last_result(""), # type: ignore + on_click=CallScriptState.setvar("last_result", 0), ), rx.button( "call_with_var_f_string", @@ -308,7 +310,7 @@ def CallScript(): "call_with_var_f_string_inline", on_click=rx.call_script( f"{rx.Var('inline_counter')} + {CallScriptState.last_result}", - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ), id="call_with_var_f_string_inline", ), @@ -316,7 +318,7 @@ def CallScript(): "call_with_var_str_cast_inline", on_click=rx.call_script( f"{rx.Var('inline_counter')!s} + {rx.Var('external_counter')!s}", - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ), id="call_with_var_str_cast_inline", ), @@ -326,7 +328,7 @@ def CallScript(): rx.Var( f"{rx.Var('inline_counter')} + {CallScriptState.last_result}" ), - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ), id="call_with_var_f_string_wrapped_inline", ), @@ -336,7 +338,7 @@ def CallScript(): rx.Var( f"{rx.Var('inline_counter')!s} + {rx.Var('external_counter')!s}" ), - callback=CallScriptState.set_last_result, # type: ignore + callback=CallScriptState.setvar("last_result"), ), id="call_with_var_str_cast_wrapped_inline", ), @@ -483,7 +485,7 @@ def test_call_script_w_var( """ assert_token(driver) last_result = driver.find_element(By.ID, "last_result") - assert last_result.get_attribute("value") == "" + assert last_result.get_attribute("value") == "0" inline_return_button = driver.find_element(By.ID, "inline_return") diff --git a/tests/integration/test_client_storage.py b/tests/integration/test_client_storage.py index 2652d6ccb..3618c779d 100644 --- a/tests/integration/test_client_storage.py +++ b/tests/integration/test_client_storage.py @@ -33,18 +33,18 @@ def ClientSide(): class ClientSideSubState(ClientSideState): # cookies with default settings c1: str = rx.Cookie() - c2: rx.Cookie = "c2 default" # type: ignore + c2: str = rx.Cookie("c2 default") # cookies with custom settings c3: str = rx.Cookie(max_age=2) # expires after 2 second - c4: rx.Cookie = rx.Cookie(same_site="strict") + c4: str = rx.Cookie(same_site="strict") c5: str = rx.Cookie(path="/foo/") # only accessible on `/foo/` c6: str = rx.Cookie(name="c6") c7: str = rx.Cookie("c7 default") # local storage with default settings l1: str = rx.LocalStorage() - l2: rx.LocalStorage = "l2 default" # type: ignore + l2: str = rx.LocalStorage("l2 default") # local storage with custom settings l3: str = rx.LocalStorage(name="l3") @@ -56,7 +56,7 @@ def ClientSide(): # Session storage s1: str = rx.SessionStorage() - s2: rx.SessionStorage = "s2 default" # type: ignore + s2: str = rx.SessionStorage("s2 default") s3: str = rx.SessionStorage(name="s3") def set_l6(self, my_param: str): @@ -87,13 +87,13 @@ def ClientSide(): rx.input( placeholder="state var", value=ClientSideState.state_var, - on_change=ClientSideState.set_state_var, # type: ignore + on_change=ClientSideState.setvar("state_var"), id="state_var", ), rx.input( placeholder="input value", value=ClientSideState.input_value, - on_change=ClientSideState.set_input_value, # type: ignore + on_change=ClientSideState.setvar("input_value"), id="input_value", ), rx.button( @@ -127,7 +127,7 @@ def ClientSide(): rx.box(ClientSideSubSubState.s1s, id="s1s"), ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) app.add_page(index, route="/foo") @@ -321,6 +321,7 @@ async def test_client_side_state( assert not driver.get_cookies() local_storage_items = local_storage.items() local_storage_items.pop("last_compiled_time", None) + local_storage_items.pop("theme", None) assert not local_storage_items # set some cookies and local storage values @@ -436,6 +437,7 @@ async def test_client_side_state( local_storage_items = local_storage.items() local_storage_items.pop("last_compiled_time", None) + local_storage_items.pop("theme", None) assert local_storage_items.pop(f"{sub_state_name}.l1") == "l1 value" assert local_storage_items.pop(f"{sub_state_name}.l2") == "l2 value" assert local_storage_items.pop("l3") == "l3 value" diff --git a/tests/integration/test_component_state.py b/tests/integration/test_component_state.py index 97624e7c5..654dc7ce9 100644 --- a/tests/integration/test_component_state.py +++ b/tests/integration/test_component_state.py @@ -30,7 +30,7 @@ def ComponentStateApp(): @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 ComponentStateApp(): 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 ComponentStateApp(): 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 44187c8ba..e6a8caef6 100644 --- a/tests/integration/test_connection_banner.py +++ b/tests/integration/test_connection_banner.py @@ -1,5 +1,6 @@ """Test case for displaying the connection banner when the websocket drops.""" +import functools from typing import Generator import pytest @@ -11,12 +12,19 @@ from reflex.testing import AppHarness, WebDriver from .utils import SessionStorage -def ConnectionBanner(): - """App with a connection banner.""" +def ConnectionBanner(is_reflex_cloud: bool = False): + """App with a connection banner. + + Args: + is_reflex_cloud: The value for config.is_reflex_cloud. + """ import asyncio import reflex as rx + # Simulate reflex cloud deploy + rx.config.get_config().is_reflex_cloud = is_reflex_cloud + class State(rx.State): foo: int = 0 @@ -31,28 +39,52 @@ def ConnectionBanner(): 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), ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) +@pytest.fixture( + params=[False, True], ids=["reflex_cloud_disabled", "reflex_cloud_enabled"] +) +def simulate_is_reflex_cloud(request) -> bool: + """Fixture to simulate reflex cloud deployment. + + Args: + request: pytest request fixture. + + Returns: + True if reflex cloud is enabled, False otherwise. + """ + return request.param + + @pytest.fixture() -def connection_banner(tmp_path) -> Generator[AppHarness, None, None]: +def connection_banner( + tmp_path, + simulate_is_reflex_cloud: bool, +) -> Generator[AppHarness, None, None]: """Start ConnectionBanner app at tmp_path via AppHarness. Args: tmp_path: pytest tmp_path fixture + simulate_is_reflex_cloud: Whether is_reflex_cloud is set for the app. Yields: running AppHarness instance """ with AppHarness.create( root=tmp_path, - app_source=ConnectionBanner, + app_source=functools.partial( + ConnectionBanner, is_reflex_cloud=simulate_is_reflex_cloud + ), + app_name="connection_banner_reflex_cloud" + if simulate_is_reflex_cloud + else "connection_banner", ) as harness: yield harness @@ -71,9 +103,42 @@ def has_error_modal(driver: WebDriver) -> bool: """ try: driver.find_element(By.XPATH, CONNECTION_ERROR_XPATH) - return True except NoSuchElementException: return False + else: + return True + + +def has_cloud_banner(driver: WebDriver) -> bool: + """Check if the cloud banner is displayed. + + Args: + driver: Selenium webdriver instance. + + Returns: + True if the banner is displayed, False otherwise. + """ + try: + driver.find_element( + By.XPATH, "//*[ contains(text(), 'You ran out of compute credits.') ]" + ) + except NoSuchElementException: + return False + else: + return True + + +def _assert_token(connection_banner, driver): + """Poll for backend to be up. + + Args: + connection_banner: AppHarness instance. + driver: Selenium webdriver instance. + """ + ss = SessionStorage(driver) + assert connection_banner._poll_for(lambda: ss.get("token") is not None), ( + "token not found" + ) @pytest.mark.asyncio @@ -87,11 +152,7 @@ async def test_connection_banner(connection_banner: AppHarness): assert connection_banner.backend is not None driver = connection_banner.frontend() - ss = SessionStorage(driver) - assert connection_banner._poll_for( - lambda: ss.get("token") is not None - ), "token not found" - + _assert_token(connection_banner, driver) assert connection_banner._poll_for(lambda: not has_error_modal(driver)) delay_button = driver.find_element(By.ID, "delay") @@ -131,3 +192,36 @@ async def test_connection_banner(connection_banner: AppHarness): # Count should have incremented after coming back up assert connection_banner.poll_for_value(counter_element, exp_not_equal="1") == "2" + + +@pytest.mark.asyncio +async def test_cloud_banner( + connection_banner: AppHarness, simulate_is_reflex_cloud: bool +): + """Test that the connection banner is displayed when the websocket drops. + + Args: + connection_banner: AppHarness instance. + simulate_is_reflex_cloud: Whether is_reflex_cloud is set for the app. + """ + assert connection_banner.app_instance is not None + assert connection_banner.backend is not None + driver = connection_banner.frontend() + + driver.add_cookie({"name": "backend-enabled", "value": "truly"}) + driver.refresh() + _assert_token(connection_banner, driver) + assert connection_banner._poll_for(lambda: not has_cloud_banner(driver)) + + driver.add_cookie({"name": "backend-enabled", "value": "false"}) + driver.refresh() + if simulate_is_reflex_cloud: + assert connection_banner._poll_for(lambda: has_cloud_banner(driver)) + else: + _assert_token(connection_banner, driver) + assert connection_banner._poll_for(lambda: not has_cloud_banner(driver)) + + driver.delete_cookie("backend-enabled") + driver.refresh() + _assert_token(connection_banner, driver) + assert connection_banner._poll_for(lambda: not has_cloud_banner(driver)) diff --git a/tests/integration/test_deploy_url.py b/tests/integration/test_deploy_url.py index 5c840d24d..207f37609 100644 --- a/tests/integration/test_deploy_url.py +++ b/tests/integration/test_deploy_url.py @@ -19,14 +19,14 @@ 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( rx.button("GOTO SELF", on_click=State.goto_self, id="goto_self") ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) diff --git a/tests/integration/test_dynamic_routes.py b/tests/integration/test_dynamic_routes.py index c210bde69..40886a601 100644 --- a/tests/integration/test_dynamic_routes.py +++ b/tests/integration/test_dynamic_routes.py @@ -49,7 +49,7 @@ def DynamicRoute(): 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 DynamicRoute(): 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 DynamicRoute(): 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 DynamicRoute(): ), 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 DynamicRoute(): 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 = rx.App(_state=rx.State) + 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 15f3c9877..707410075 100644 --- a/tests/integration/test_event_actions.py +++ b/tests/integration/test_event_actions.py @@ -63,16 +63,16 @@ def TestEventAction(): 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 TestEventAction(): 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 TestEventAction(): 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,47 +116,47 @@ def TestEventAction(): 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) + app = rx.App(_state=rx.State) app.add_page(index) diff --git a/tests/integration/test_event_chain.py b/tests/integration/test_event_chain.py index c4121ee94..df571e884 100644 --- a/tests/integration/test_event_chain.py +++ b/tests/integration/test_event_chain.py @@ -43,32 +43,32 @@ def EventChain(): 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 EventChain(): 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 EventChain(): 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 EventChain(): @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): @@ -144,7 +144,7 @@ def EventChain(): time.sleep(0.5) self.interim_value = "final" - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) token_input = rx.input( value=State.router.session.client_token, is_read_only=True, id="token" @@ -193,12 +193,12 @@ def EventChain(): 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 EventChain(): 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 EventChain(): "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 EventChain(): 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 a645d1de6..71858b899 100644 --- a/tests/integration/test_exception_handlers.py +++ b/tests/integration/test_exception_handlers.py @@ -39,7 +39,7 @@ def TestApp(): """ print(1 / number) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): @@ -51,12 +51,12 @@ def TestApp(): ), 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_form_submit.py b/tests/integration/test_form_submit.py index ea8750595..bdf54173c 100644 --- a/tests/integration/test_form_submit.py +++ b/tests/integration/test_form_submit.py @@ -30,7 +30,7 @@ def FormSubmit(form_component): def form_submit(self, form_data: Dict): self.form_data = form_data - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): @@ -90,7 +90,7 @@ def FormSubmitName(form_component): def form_submit(self, form_data: Dict): self.form_data = form_data - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): diff --git a/tests/integration/test_input.py b/tests/integration/test_input.py index e9fec7dc1..5f2948feb 100644 --- a/tests/integration/test_input.py +++ b/tests/integration/test_input.py @@ -16,7 +16,7 @@ def FullyControlledInput(): class State(rx.State): text: str = "initial" - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): @@ -26,11 +26,11 @@ def FullyControlledInput(): ), 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 d79273fbc..24dd7df6a 100644 --- a/tests/integration/test_lifespan.py +++ b/tests/integration/test_lifespan.py @@ -65,7 +65,7 @@ def LifespanApp(): 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 1938672a3..a1df015bf 100644 --- a/tests/integration/test_login_flow.py +++ b/tests/integration/test_login_flow.py @@ -31,8 +31,8 @@ def LoginSample(): 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"), @@ -45,7 +45,7 @@ def LoginSample(): rx.button("Do it", on_click=State.login, id="doit"), ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) app.add_page(login) diff --git a/tests/integration/test_media.py b/tests/integration/test_media.py index 649038a7e..f3ce65c87 100644 --- a/tests/integration/test_media.py +++ b/tests/integration/test_media.py @@ -19,7 +19,7 @@ def MediaApp(): 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 MediaApp(): 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_server_side_event.py b/tests/integration/test_server_side_event.py index f04cc3beb..3050a4e36 100644 --- a/tests/integration/test_server_side_event.py +++ b/tests/integration/test_server_side_event.py @@ -38,7 +38,7 @@ def ServerSideEvent(): def set_value_return_c(self): return rx.set_value("c", "") - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): diff --git a/tests/integration/test_state_inheritance.py b/tests/integration/test_state_inheritance.py index 6b93a2ed7..f544fcc92 100644 --- a/tests/integration/test_state_inheritance.py +++ b/tests/integration/test_state_inheritance.py @@ -131,7 +131,7 @@ def StateInheritance(): 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 StateInheritance(): 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 StateInheritance(): 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 StateInheritance(): 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 0331c15d6..a0df05f52 100644 --- a/tests/integration/test_upload.py +++ b/tests/integration/test_upload.py @@ -80,7 +80,7 @@ def UploadFile(): ), 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 UploadFile(): ), 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 UploadFile(): ), rx.vstack( rx.foreach( - UploadState.progress_dicts, # type: ignore + UploadState.progress_dicts, lambda d: rx.text(d.to_string()), ) ), @@ -146,7 +146,7 @@ def UploadFile(): ), 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", ), @@ -166,7 +166,7 @@ def UploadFile(): rx.text(UploadState.event_order.to_string(), id="event-order"), ) - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) app.add_page(index) diff --git a/tests/integration/test_var_operations.py b/tests/integration/test_var_operations.py index 7a7c8328d..9b952c575 100644 --- a/tests/integration/test_var_operations.py +++ b/tests/integration/test_var_operations.py @@ -7,42 +7,38 @@ from selenium.webdriver.common.by import By 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) + 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 VarOperations(): 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 VarOperations(): 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 VarOperations(): ), # 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 VarOperations(): ), # 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 VarOperations(): 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 VarOperations(): 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 VarOperations(): ), 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"), @@ -598,6 +600,11 @@ def VarOperations(): ), id="foreach_in_match", ), + # Literal range var in a foreach + rx.box(rx.foreach(range(42, 80, 27), rx.text.span), id="range_in_foreach1"), + rx.box(rx.foreach(range(42, 80, 3), rx.text.span), id="range_in_foreach2"), + rx.box(rx.foreach(range(42, 20, -6), rx.text.span), id="range_in_foreach3"), + rx.box(rx.foreach(range(42, 43, 5), rx.text.span), id="range_in_foreach4"), ) @@ -797,6 +804,11 @@ def test_var_operations(driver, var_operations: AppHarness): ("memo_comp_nested", "345"), # foreach in a match ("foreach_in_match", "first\nsecond\nthird"), + # literal range in a foreach + ("range_in_foreach1", "4269"), + ("range_in_foreach2", "42454851545760636669727578"), + ("range_in_foreach3", "42363024"), + ("range_in_foreach4", "42"), ] for tag, expected in tests: diff --git a/tests/integration/tests_playwright/test_appearance.py b/tests/integration/tests_playwright/test_appearance.py index 60aeeaa6b..d325b183f 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 fafd15c42..2ac516d4a 100644 --- a/tests/integration/tests_playwright/test_datetime_operations.py +++ b/tests/integration/tests_playwright/test_datetime_operations.py @@ -16,7 +16,7 @@ def DatetimeOperationsApp(): date2: datetime = datetime(2031, 1, 1) date3: datetime = datetime(2021, 1, 1) - app = rx.App(state=DtOperationsState) + app = rx.App(_state=DtOperationsState) @app.add_page def index(): @@ -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 9510bd358..3c29d769a 100644 --- a/tests/integration/tests_playwright/test_link_hover.py +++ b/tests/integration/tests_playwright/test_link_hover.py @@ -29,7 +29,7 @@ def LinkApp(): 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/integration/tests_playwright/test_table.py b/tests/integration/tests_playwright/test_table.py index db716aa5b..a88c4a621 100644 --- a/tests/integration/tests_playwright/test_table.py +++ b/tests/integration/tests_playwright/test_table.py @@ -3,7 +3,7 @@ from typing import Generator import pytest -from playwright.sync_api import Page +from playwright.sync_api import Page, expect from reflex.testing import AppHarness @@ -20,7 +20,7 @@ def Table(): """App using table component.""" import reflex as rx - app = rx.App(state=rx.State) + app = rx.App(_state=rx.State) @app.add_page def index(): @@ -87,12 +87,14 @@ def test_table(page: Page, table_app: AppHarness): table = page.get_by_role("table") # Check column headers - headers = table.get_by_role("columnheader").all_inner_texts() - assert headers == expected_col_headers + headers = table.get_by_role("columnheader") + for header, exp_value in zip(headers.all(), expected_col_headers, strict=True): + expect(header).to_have_text(exp_value) # Check rows headers - rows = table.get_by_role("rowheader").all_inner_texts() - assert rows == expected_row_headers + rows = table.get_by_role("rowheader") + for row, expected_row in zip(rows.all(), expected_row_headers, strict=True): + expect(row).to_have_text(expected_row) # Check cells rows = table.get_by_role("cell").all_inner_texts() diff --git a/tests/units/assets/test_assets.py b/tests/units/assets/test_assets.py index b957f1902..dc444cfad 100644 --- a/tests/units/assets/test_assets.py +++ b/tests/units/assets/test_assets.py @@ -37,19 +37,6 @@ def test_shared_asset() -> None: assert not Path(Path.cwd() / "assets/external").exists() -def test_deprecated_x_asset(capsys) -> None: - """Test that the deprecated asset function raises a warning. - - Args: - capsys: Pytest fixture that captures stdout and stderr. - """ - assert rx.asset("custom_script.js", shared=True) == rx._x.asset("custom_script.js") - assert ( - "DeprecationWarning: rx._x.asset has been deprecated in version 0.6.6" - in capsys.readouterr().out - ) - - @pytest.mark.parametrize( "path,shared", [ diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 22f5c8483..50088e728 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: @@ -100,10 +100,10 @@ def test_compile_imports(import_dict: ParsedImportDict, test_dicts: List[dict]): test_dicts: The expected output. """ imports = utils.compile_imports(import_dict) - for import_dict, test_dict in zip(imports, test_dicts): + 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 c1295fb41..31cd75b47 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 e88f35c9a..ac073ed29 100644 --- a/tests/units/components/core/test_cond.py +++ b/tests/units/components/core/test_cond.py @@ -14,7 +14,7 @@ from reflex.vars.base import LiteralVar, Var, computed_var @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 79c258dfb..bebb2587d 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 @@ def test_html_fstring_create(): 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 f09e800e5..11602b77a 100644 --- a/tests/units/components/core/test_match.py +++ b/tests/units/components/core/test_match.py @@ -1,8 +1,9 @@ -from typing import Dict, List, Tuple +from typing import List, Mapping, Tuple import pytest import reflex as rx +from reflex.components.component import Component from reflex.components.core.match import Match from reflex.state import BaseState from reflex.utils.exceptions import MatchTypeError @@ -29,7 +30,9 @@ def test_match_components(): rx.text("default value"), ) match_comp = Match.create(MatchState.value, *match_case_tuples) - match_dict = match_comp.render() # type: ignore + + assert isinstance(match_comp, Component) + match_dict = match_comp.render() assert match_dict["name"] == "Fragment" [match_child] = match_dict["children"] @@ -42,7 +45,7 @@ def test_match_components(): assert match_cases[0][0]._js_expr == "1" assert match_cases[0][0]._var_type is int - first_return_value_render = match_cases[0][1].render() + first_return_value_render = match_cases[0][1] assert first_return_value_render["name"] == "RadixThemesText" assert first_return_value_render["children"][0]["contents"] == '{"first value"}' @@ -50,35 +53,35 @@ def test_match_components(): assert match_cases[1][0]._var_type is int assert match_cases[1][1]._js_expr == "3" assert match_cases[1][1]._var_type is int - second_return_value_render = match_cases[1][2].render() + second_return_value_render = match_cases[1][2] assert second_return_value_render["name"] == "RadixThemesText" assert second_return_value_render["children"][0]["contents"] == '{"second value"}' assert match_cases[2][0]._js_expr == "[1, 2]" assert match_cases[2][0]._var_type == List[int] - third_return_value_render = match_cases[2][1].render() + third_return_value_render = match_cases[2][1] assert third_return_value_render["name"] == "RadixThemesText" assert third_return_value_render["children"][0]["contents"] == '{"third value"}' assert match_cases[3][0]._js_expr == '"random"' assert match_cases[3][0]._var_type is str - fourth_return_value_render = match_cases[3][1].render() + fourth_return_value_render = match_cases[3][1] assert fourth_return_value_render["name"] == "RadixThemesText" assert fourth_return_value_render["children"][0]["contents"] == '{"fourth value"}' assert match_cases[4][0]._js_expr == '({ ["foo"] : "bar" })' - assert match_cases[4][0]._var_type == Dict[str, str] - fifth_return_value_render = match_cases[4][1].render() + assert match_cases[4][0]._var_type == Mapping[str, str] + fifth_return_value_render = match_cases[4][1] assert fifth_return_value_render["name"] == "RadixThemesText" assert fifth_return_value_render["children"][0]["contents"] == '{"fifth value"}' assert match_cases[5][0]._js_expr == f"({MatchState.get_name()}.num + 1)" assert match_cases[5][0]._var_type is int - fifth_return_value_render = match_cases[5][1].render() + fifth_return_value_render = match_cases[5][1] assert fifth_return_value_render["name"] == "RadixThemesText" assert fifth_return_value_render["children"][0]["contents"] == '{"sixth value"}' - default = match_child["default"].render() + default = match_child["default"] assert default["name"] == "RadixThemesText" assert default["children"][0]["contents"] == '{"default value"}' @@ -151,9 +154,10 @@ 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 + assert isinstance(match_comp, Component) + default = match_comp.render()["children"][0]["default"] - assert isinstance(default, Fragment) + assert isinstance(default, dict) and default["name"] == Fragment.__name__ def test_match_on_var_no_default(): diff --git a/tests/units/components/core/test_upload.py b/tests/units/components/core/test_upload.py index 710baa161..efade7b63 100644 --- a/tests/units/components/core/test_upload.py +++ b/tests/units/components/core/test_upload.py @@ -5,7 +5,7 @@ from reflex.components.core.upload import ( 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/conftest.py b/tests/units/components/datadisplay/conftest.py index 13c571c8c..188e887c4 100644 --- a/tests/units/components/datadisplay/conftest.py +++ b/tests/units/components/datadisplay/conftest.py @@ -1,7 +1,5 @@ """Data display component tests fixtures.""" -from typing import List - import pandas as pd import pytest @@ -54,11 +52,11 @@ def data_table_state3(): """ class DataTableState(BaseState): - _data: List = [] - _columns: List = ["col1", "col2"] + _data: list = [] + _columns: list = ["col1", "col2"] @rx.var - def data(self) -> List: + def data(self) -> list: return self._data @rx.var @@ -77,15 +75,15 @@ def data_table_state4(): """ class DataTableState(BaseState): - _data: List = [] - _columns: List = ["col1", "col2"] + _data: list = [] + _columns: list[str] = ["col1", "col2"] @rx.var def data(self): return self._data @rx.var - def columns(self) -> List: + def columns(self) -> list: return self._columns return DataTableState diff --git a/tests/units/components/datadisplay/test_code.py b/tests/units/components/datadisplay/test_code.py index 6b7168756..db0120fe1 100644 --- a/tests/units/components/datadisplay/test_code.py +++ b/tests/units/components/datadisplay/test_code.py @@ -10,4 +10,4 @@ from reflex.components.datadisplay.code import CodeBlock, Theme 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 b3d31ea32..2dece464a 100644 --- a/tests/units/components/datadisplay/test_datatable.py +++ b/tests/units/components/datadisplay/test_datatable.py @@ -4,6 +4,7 @@ import pytest import reflex as rx from reflex.components.gridjs.datatable import DataTable from reflex.utils import types +from reflex.utils.exceptions import UntypedComputedVarError from reflex.utils.serializers import serialize, serialize_dataframe @@ -13,7 +14,8 @@ from reflex.utils.serializers import serialize, serialize_dataframe pytest.param( { "data": pd.DataFrame( - [["foo", "bar"], ["foo1", "bar1"]], columns=["column1", "column2"] + [["foo", "bar"], ["foo1", "bar1"]], + columns=["column1", "column2"], # pyright: ignore [reportArgumentType] ) }, "data", @@ -75,17 +77,17 @@ def test_invalid_props(props): [ ( "data_table_state2", - "Annotation of the computed var assigned to the data field should be provided.", + "Computed var 'data' must have a type annotation.", True, ), ( "data_table_state3", - "Annotation of the computed var assigned to the column field should be provided.", + "Computed var 'columns' must have a type annotation.", False, ), ( "data_table_state4", - "Annotation of the computed var assigned to the data field should be provided.", + "Computed var 'data' must have a type annotation.", False, ), ], @@ -99,7 +101,7 @@ def test_computed_var_without_annotation(fixture, request, err_msg, is_data_fram err_msg: expected error message. is_data_frame: whether data field is a pandas dataframe. """ - with pytest.raises(ValueError) as err: + with pytest.raises(UntypedComputedVarError) as err: if is_data_frame: DataTable.create(data=request.getfixturevalue(fixture).data) else: @@ -113,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 eb473ba06..cc05c35b0 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 5f3ba2d37..69b5e7b63 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 742bd8c38..519ca735e 100644 --- a/tests/units/components/media/test_image.py +++ b/tests/units/components/media/test_image.py @@ -4,7 +4,7 @@ import pytest 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 674873b69..8cffa6e0e 100644 --- a/tests/units/components/test_component.py +++ b/tests/units/components/test_component.py @@ -19,6 +19,7 @@ from reflex.constants import EventTriggers from reflex.event import ( EventChain, EventHandler, + JavascriptInputEvent, input_event, no_args_event_spec, parse_args_spec, @@ -27,10 +28,15 @@ from reflex.event import ( from reflex.state import BaseState from reflex.style import Style from reflex.utils import imports -from reflex.utils.exceptions import EventFnArgMismatch +from reflex.utils.exceptions import ( + ChildrenTypeError, + EventFnArgMismatchError, + EventHandlerArgTypeMismatchError, +) from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports from reflex.vars import VarData from reflex.vars.base import LiteralVar, Var +from reflex.vars.object import ObjectVar @pytest.fixture @@ -94,11 +100,14 @@ def component2() -> Type[Component]: A test component. """ + def on_prop_event_spec(e0: Any): + return [e0] + class TestComponent2(Component): # A test list prop. arr: Var[List[str]] - on_prop_event: EventHandler[lambda e0: [e0]] + on_prop_event: EventHandler[on_prop_event_spec] def get_event_triggers(self) -> Dict[str, Any]: """Test controlled triggers. @@ -444,8 +453,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"' @@ -461,8 +470,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"' @@ -645,14 +654,17 @@ def test_create_filters_none_props(test_component): assert str(component.style["text-align"]) == '"center"' -@pytest.mark.parametrize("children", [((None,),), ("foo", ("bar", (None,)))]) +@pytest.mark.parametrize( + "children", + [ + ((None,),), + ("foo", ("bar", (None,))), + ({"foo": "bar"},), + ], +) def test_component_create_unallowed_types(children, test_component): - with pytest.raises(TypeError) as err: + with pytest.raises(ChildrenTypeError): test_component.create(*children) - assert ( - err.value.args[0] - == "Children of Reflex components must be other components, state vars, or primitive Python types. Got child None of type ." - ) @pytest.mark.parametrize( @@ -815,10 +827,14 @@ def test_component_create_unpack_tuple_child(test_component, element, expected): assert fragment_wrapper.render() == expected +class _Obj(Base): + custom: int = 0 + + class C1State(BaseState): """State for testing C1 component.""" - def mock_handler(self, _e, _bravo, _charlie): + def mock_handler(self, _e: JavascriptInputEvent, _bravo: dict, _charlie: _Obj): """Mock handler.""" pass @@ -826,11 +842,13 @@ class C1State(BaseState): def test_component_event_trigger_arbitrary_args(): """Test that we can define arbitrary types for the args of an event trigger.""" - class Obj(Base): - custom: int = 0 - - def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj): - return [_e.target.value, bravo["nested"], charlie.custom + 42] + def on_foo_spec( + _e: ObjectVar[JavascriptInputEvent], + alpha: Var[str], + bravo: dict[str, Any], + charlie: ObjectVar[_Obj], + ): + return [_e.target.value, bravo["nested"], charlie.custom.to(int) + 42] class C1(Component): library = "/local" @@ -842,13 +860,7 @@ def test_component_event_trigger_arbitrary_args(): "on_foo": on_foo_spec, } - comp = C1.create(on_foo=C1State.mock_handler) - - assert comp.render()["props"][0] == ( - "onFoo={((__e, _alpha, _bravo, _charlie) => (addEvents(" - f'[(Event("{C1State.get_full_name()}.mock_handler", ({{ ["_e"] : __e["target"]["value"], ["_bravo"] : _bravo["nested"], ["_charlie"] : (_charlie["custom"] + 42) }}), ({{ }})))], ' - "[__e, _alpha, _bravo, _charlie], ({ }))))}" - ) + C1.create(on_foo=C1State.mock_handler) def test_create_custom_component(my_component): @@ -905,30 +917,29 @@ def test_invalid_event_handler_args(component2, test_state): test_state: A test state. """ # EventHandler args must match - with pytest.raises(EventFnArgMismatch): + with pytest.raises(EventFnArgMismatchError): component2.create(on_click=test_state.do_something_arg) # Multiple EventHandler args: all must match - with pytest.raises(EventFnArgMismatch): + with pytest.raises(EventFnArgMismatchError): component2.create( on_click=[test_state.do_something_arg, test_state.do_something] ) - # Enable when 0.7.0 happens # # Event Handler types must match - # with pytest.raises(EventHandlerArgTypeMismatch): - # component2.create( - # on_user_visited_count_changed=test_state.do_something_with_bool # noqa: ERA001 RUF100 - # ) # noqa: ERA001 RUF100 - # with pytest.raises(EventHandlerArgTypeMismatch): - # component2.create(on_user_list_changed=test_state.do_something_with_int) #noqa: ERA001 - # with pytest.raises(EventHandlerArgTypeMismatch): - # component2.create(on_user_list_changed=test_state.do_something_with_list_int) #noqa: ERA001 + with pytest.raises(EventHandlerArgTypeMismatchError): + component2.create( + on_user_visited_count_changed=test_state.do_something_with_bool + ) + with pytest.raises(EventHandlerArgTypeMismatchError): + component2.create(on_user_list_changed=test_state.do_something_with_int) + with pytest.raises(EventHandlerArgTypeMismatchError): + component2.create(on_user_list_changed=test_state.do_something_with_list_int) - # component2.create(on_open=test_state.do_something_with_int) #noqa: ERA001 - # component2.create(on_open=test_state.do_something_with_bool) #noqa: ERA001 - # component2.create(on_user_visited_count_changed=test_state.do_something_with_int) #noqa: ERA001 - # component2.create(on_user_list_changed=test_state.do_something_with_list_str) #noqa: ERA001 + component2.create(on_open=test_state.do_something_with_int) + component2.create(on_open=test_state.do_something_with_bool) + component2.create(on_user_visited_count_changed=test_state.do_something_with_int) + component2.create(on_user_list_changed=test_state.do_something_with_list_str) # lambda cannot return weird values. with pytest.raises(ValueError): @@ -941,15 +952,15 @@ def test_invalid_event_handler_args(component2, test_state): ) # lambda signature must match event trigger. - with pytest.raises(EventFnArgMismatch): + with pytest.raises(EventFnArgMismatchError): component2.create(on_click=lambda _: test_state.do_something_arg(1)) # lambda returning EventHandler must match spec - with pytest.raises(EventFnArgMismatch): + with pytest.raises(EventFnArgMismatchError): component2.create(on_click=lambda: test_state.do_something_arg) # Mixed EventSpec and EventHandler must match spec. - with pytest.raises(EventFnArgMismatch): + with pytest.raises(EventFnArgMismatchError): component2.create( on_click=lambda: [ test_state.do_something_arg(1), @@ -1318,7 +1329,7 @@ class EventState(rx.State): ), pytest.param( rx.fragment(class_name=[TEST_VAR, "other-class"]), - [LiteralVar.create([TEST_VAR, "other-class"]).join(" ")], + [Var.create([TEST_VAR, "other-class"]).join(" ")], id="fstring-dual-class_name", ), pytest.param( @@ -1353,17 +1364,17 @@ class EventState(rx.State): 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", ), @@ -1373,17 +1384,17 @@ class EventState(rx.State): 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", ), @@ -1436,6 +1447,7 @@ def test_get_vars(component, exp_vars): for comp_var, exp_var in zip( comp_vars, sorted(exp_vars, key=lambda v: v._js_expr), + strict=True, ): assert comp_var.equals(exp_var) @@ -1471,7 +1483,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( @@ -1544,11 +1556,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)) ), ) ) @@ -1603,12 +1615,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)), ) ), @@ -1671,13 +1683,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 + ) ), ) ) @@ -1798,21 +1810,15 @@ def test_custom_component_declare_event_handlers_in_fields(): """ return { **super().get_event_triggers(), - "on_a": lambda e0: [e0], "on_b": input_event, - "on_c": lambda e0: [], "on_d": lambda: [], "on_e": lambda: [], - "on_f": lambda a, b, c: [c, b, a], } class TestComponent(Component): - on_a: EventHandler[lambda e0: [e0]] on_b: EventHandler[input_event] - on_c: EventHandler[no_args_event_spec] on_d: EventHandler[no_args_event_spec] on_e: EventHandler - on_f: EventHandler[lambda a, b, c: [c, b, a]] custom_component = ReferenceComponent.create() test_component = TestComponent.create() @@ -1823,6 +1829,7 @@ def test_custom_component_declare_event_handlers_in_fields(): for v1, v2 in zip( parse_args_spec(test_triggers[trigger_name]), parse_args_spec(custom_triggers[trigger_name]), + strict=True, ): assert v1.equals(v2) @@ -1864,7 +1871,7 @@ def test_invalid_event_trigger(): ) 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): @@ -1876,7 +1883,7 @@ def test_component_add_imports(tags): ) 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"} @@ -1908,7 +1915,7 @@ def test_component_add_hooks(): pass class GrandchildComponent1(ChildComponent1): - def add_hooks(self): + def add_hooks(self): # pyright: ignore [reportIncompatibleMethodOverride] return [ "const hook2 = 43", "const hook3 = 44", @@ -1921,11 +1928,11 @@ def test_component_add_hooks(): ] 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", @@ -2000,7 +2007,7 @@ def test_component_add_custom_code(): ] class GrandchildComponent2(ChildComponent1): - def _get_custom_code(self): + def _get_custom_code(self): # pyright: ignore [reportIncompatibleMethodOverride] return "const custom_code5 = 46" class GreatGrandchildComponent2(GrandchildComponent2): @@ -2096,11 +2103,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): @@ -2114,7 +2121,7 @@ def test_add_style_embedded_vars(test_state: BaseState): 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 5e9abbb1f..12f3b0dbe 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 fb6229aca..2ee290ea3 100644 --- a/tests/units/conftest.py +++ b/tests/units/conftest.py @@ -1,11 +1,8 @@ """Test fixtures.""" import asyncio -import contextlib -import os import platform import uuid -from pathlib import Path from typing import Dict, Generator, Type from unittest import mock @@ -14,6 +11,7 @@ import pytest from reflex.app import App from reflex.event import EventSpec from reflex.model import ModelRegistry +from reflex.testing import chdir from reflex.utils import prerequisites from .states import ( @@ -97,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 @@ -107,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 @@ -145,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: @@ -172,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: @@ -181,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", @@ -191,33 +189,6 @@ def router_data(router_data_headers) -> Dict[str, str]: } -# borrowed from py3.11 -class chdir(contextlib.AbstractContextManager): - """Non thread-safe context manager to change the current working directory.""" - - def __init__(self, path): - """Prepare contextmanager. - - Args: - path: the path to change to - """ - self.path = path - self._old_cwd = [] - - def __enter__(self): - """Save current directory and perform chdir.""" - self._old_cwd.append(Path.cwd()) - os.chdir(self.path) - - def __exit__(self, *excinfo): - """Change back to previous directory on stack. - - Args: - excinfo: sys.exc_info captured in the context block - """ - os.chdir(self._old_cwd.pop()) - - @pytest.fixture def tmp_working_dir(tmp_path): """Create a temporary directory and chdir to it. diff --git a/tests/units/middleware/test_hydrate_middleware.py b/tests/units/middleware/test_hydrate_middleware.py index 9ee8d8d25..7b02f8515 100644 --- a/tests/units/middleware/test_hydrate_middleware.py +++ b/tests/units/middleware/test_hydrate_middleware.py @@ -41,7 +41,7 @@ async def test_preprocess_no_events(hydrate_middleware, event1, mocker): mocker.patch("reflex.state.State.class_subclasses", {TestState}) state = State() update = await hydrate_middleware.preprocess( - app=App(state=State), + app=App(_state=State), event=event1, state=state, ) diff --git a/tests/units/states/mutation.py b/tests/units/states/mutation.py index b05f558a1..ad658bbd0 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 f805f83ec..058174a1b 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 @@ def test_custom_auth_admin() -> Type[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 @@ -236,14 +236,14 @@ def test_add_page_default_route(app: App, index_page, about_page): index_page: The index page. about_page: The about page. """ - assert app.pages == {} - assert app.unevaluated_pages == {} + assert app._pages == {} + assert app._unevaluated_pages == {} app.add_page(index_page) app._compile_page("index") - assert app.pages.keys() == {"index"} + assert app._pages.keys() == {"index"} app.add_page(about_page) app._compile_page("about") - assert app.pages.keys() == {"index", "about"} + assert app._pages.keys() == {"index", "about"} def test_add_page_set_route(app: App, index_page, windows_platform: bool): @@ -255,10 +255,10 @@ def test_add_page_set_route(app: App, index_page, windows_platform: bool): windows_platform: Whether the system is windows. """ route = "test" if windows_platform else "/test" - assert app.unevaluated_pages == {} + assert app._unevaluated_pages == {} app.add_page(index_page, route=route) app._compile_page("test") - assert app.pages.keys() == {"test"} + assert app._pages.keys() == {"test"} def test_add_page_set_route_dynamic(index_page, windows_platform: bool): @@ -268,18 +268,18 @@ def test_add_page_set_route_dynamic(index_page, windows_platform: bool): index_page: The index page. windows_platform: Whether the system is windows. """ - app = App(state=EmptyState) - assert app.state is not None + app = App(_state=EmptyState) + assert app._state is not None route = "/test/[dynamic]" - assert app.unevaluated_pages == {} + assert app._unevaluated_pages == {} app.add_page(index_page, route=route) app._compile_page("test/[dynamic]") - assert app.pages.keys() == {"test/[dynamic]"} - assert "dynamic" in app.state.computed_vars - assert app.state.computed_vars["dynamic"]._deps(objclass=EmptyState) == { - constants.ROUTER + assert app._pages.keys() == {"test/[dynamic]"} + assert "dynamic" in app._state.computed_vars + assert app._state.computed_vars["dynamic"]._deps(objclass=EmptyState) == { + EmptyState.get_full_name(): {constants.ROUTER}, } - assert constants.ROUTER in app.state()._computed_var_dependencies + assert constants.ROUTER in app._state()._var_dependencies def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool): @@ -291,9 +291,9 @@ def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool) windows_platform: Whether the system is windows. """ route = "test\\nested" if windows_platform else "/test/nested" - assert app.unevaluated_pages == {} + assert app._unevaluated_pages == {} app.add_page(index_page, route=route) - assert app.unevaluated_pages.keys() == {route.strip(os.path.sep)} + assert app._unevaluated_pages.keys() == {route.strip(os.path.sep)} def test_add_page_invalid_api_route(app: App, index_page): @@ -413,13 +413,13 @@ async def test_initialize_with_state(test_state: Type[ATestState], token: str): test_state: The default state. token: a Token. """ - app = App(state=test_state) - assert app.state == test_state + app = App(_state=test_state) + assert app._state == test_state # 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() @@ -432,7 +432,7 @@ async def test_set_and_get_state(test_state): Args: test_state: The default state. """ - app = App(state=test_state) + app = App(_state=test_state) # Create two tokens. token1 = str(uuid.uuid4()) + f"_{test_state.get_full_name()}" @@ -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,17 +469,17 @@ 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( + async for result in state._process( Event( token=token, name=f"{test_state.get_name()}.set_int_val", router_data={"pathname": "/", "query": {}}, payload={"value": 50}, ) - ).__anext__() - assert result.delta == {test_state.get_name(): {"int_val": 50}} + ): + assert result.delta == {test_state.get_name(): {"int_val": 50}} @pytest.mark.asyncio @@ -583,18 +583,17 @@ async def test_list_mutation_detection__plain_list( token: a Token. """ for event_name, expected_delta in event_tuples: - result = await list_mutation_state._process( + async for result in list_mutation_state._process( Event( token=token, name=f"{list_mutation_state.get_name()}.{event_name}", router_data={"pathname": "/", "query": {}}, payload={}, ) - ).__anext__() - - # prefix keys in expected_delta with the state name - expected_delta = {list_mutation_state.get_name(): expected_delta} - assert result.delta == expected_delta + ): + # prefix keys in expected_delta with the state name + expected_delta = {list_mutation_state.get_name(): expected_delta} + assert result.delta == expected_delta @pytest.mark.asyncio @@ -709,19 +708,18 @@ async def test_dict_mutation_detection__plain_list( token: a Token. """ for event_name, expected_delta in event_tuples: - result = await dict_mutation_state._process( + async for result in dict_mutation_state._process( Event( token=token, name=f"{dict_mutation_state.get_name()}.{event_name}", router_data={"pathname": "/", "query": {}}, payload={}, ) - ).__anext__() + ): + # prefix keys in expected_delta with the state name + expected_delta = {dict_mutation_state.get_name(): expected_delta} - # prefix keys in expected_delta with the state name - expected_delta = {dict_mutation_state.get_name(): expected_delta} - - assert result.delta == expected_delta + assert result.delta == expected_delta @pytest.mark.asyncio @@ -772,7 +770,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 +793,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 @@ -827,7 +825,7 @@ async def test_upload_file_without_annotation(state, tmp_path, token): token: a Token. """ state._tmp_path = tmp_path - app = App(state=State) + app = App(_state=State) request_mock = unittest.mock.Mock() request_mock.headers = { @@ -861,7 +859,7 @@ async def test_upload_file_background(state, tmp_path, token): token: a Token. """ state._tmp_path = tmp_path - app = App(state=State) + app = App(_state=State) request_mock = unittest.mock.Mock() request_mock.headers = { @@ -917,7 +915,7 @@ class DynamicState(BaseState): """ 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( @@ -938,10 +936,10 @@ def test_dynamic_arg_shadow( """ arg_name = "counter" route = f"/test/[{arg_name}]" - app = app_module_mock.app = App(state=DynamicState) - assert app.state is not None + 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( @@ -963,7 +961,7 @@ def test_multiple_dynamic_args( arg_name = "my_arg" route = f"/test/[{arg_name}]" route2 = f"/test2/[{arg_name}]" - app = app_module_mock.app = App(state=EmptyState) + app = app_module_mock.app = App(_state=EmptyState) app.add_page(index_page, route=route) app.add_page(index_page, route=route2) @@ -990,16 +988,16 @@ async def test_dynamic_route_var_route_change_completed_on_load( """ arg_name = "dynamic" route = f"/test/[{arg_name}]" - 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 - 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) == { - constants.ROUTER + 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) + 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) == { + DynamicState.get_full_name(): {constants.ROUTER}, } - assert constants.ROUTER in app.state()._computed_var_dependencies + assert constants.ROUTER in app._state()._var_dependencies substate_token = _substate_key(token, DynamicState) sid = "mock_sid" @@ -1022,7 +1020,7 @@ async def test_dynamic_route_var_route_change_completed_on_load( 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, ) @@ -1174,7 +1172,7 @@ async def test_process_events(mocker, token: str): "headers": {}, "ip": "127.0.0.1", } - app = App(state=GenState) + app = App(_state=GenState) mocker.patch.object(app, "_postprocess", AsyncMock()) event = Event( @@ -1190,7 +1188,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() @@ -1220,13 +1218,13 @@ def test_overlay_component( overlay_component: The overlay_component to pass to App. exp_page_child: The type of the expected child in the page fragment. """ - app = App(state=state, overlay_component=overlay_component) + app = App(_state=state, overlay_component=overlay_component) app._setup_overlay_component() if exp_page_child is None: 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 +1233,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, ) @@ -1243,12 +1241,12 @@ def test_overlay_component( # overlay components are wrapped during compile only app._compile_page("test") app._setup_overlay_component() - page = app.pages["test"] + page = app._pages["test"] 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 @@ -1276,12 +1274,23 @@ def compilable_app(tmp_path) -> Generator[tuple[App, Path], None, None]: yield app, web_dir -def test_app_wrap_compile_theme(compilable_app: tuple[App, Path]): +@pytest.mark.parametrize( + "react_strict_mode", + [True, False], +) +def test_app_wrap_compile_theme( + react_strict_mode: bool, compilable_app: tuple[App, Path], mocker +): """Test that the radix theme component wraps the app. Args: + react_strict_mode: Whether to use React Strict Mode. compilable_app: compilable_app fixture. + mocker: pytest mocker object. """ + conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode) + mocker.patch("reflex.config._get_config", return_value=conf) + app, web_dir = compilable_app app.theme = rx.theme(accent_color="plum") app._compile() @@ -1292,42 +1301,55 @@ def test_app_wrap_compile_theme(compilable_app: tuple[App, Path]): assert ( "function AppWrap({children}) {" "return (" - "" + + ("" if react_strict_mode else "") + + "" "" "" "{children}" "" "" "" - ")" + + ("" if react_strict_mode else "") + + ")" "}" ) in "".join(app_js_lines) -def test_app_wrap_priority(compilable_app: tuple[App, Path]): +@pytest.mark.parametrize( + "react_strict_mode", + [True, False], +) +def test_app_wrap_priority( + react_strict_mode: bool, compilable_app: tuple[App, Path], mocker +): """Test that the app wrap components are wrapped in the correct order. Args: + react_strict_mode: Whether to use React Strict Mode. compilable_app: compilable_app fixture. + mocker: pytest mocker object. """ + conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode) + mocker.patch("reflex.config._get_config", return_value=conf) + app, web_dir = compilable_app 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(): @@ -1341,8 +1363,7 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]): ] assert ( "function AppWrap({children}) {" - "return (" - "" + "return (" + ("" if react_strict_mode else "") + "" '' "" "" @@ -1352,8 +1373,7 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]): "" "" "" - "" - ")" + "" + ("" if react_strict_mode else "") + ")" "}" ) in "".join(app_js_lines) @@ -1361,52 +1381,52 @@ def test_app_wrap_priority(compilable_app: tuple[App, Path]): def test_app_state_determination(): """Test that the stateless status of an app is determined correctly.""" a1 = App() - assert a1.state is None + assert a1._state is None # No state, no router, no event handlers. a1.add_page(rx.box("Index"), route="/") - assert a1.state is None + assert a1._state is None # Add a page with `on_load` enables state. a1.add_page(rx.box("About"), route="/about", on_load=rx.console_log("")) a1._compile_page("about") - assert a1.state is not None + assert a1._state is not None a2 = App() - assert a2.state is None + assert a2._state is None # Referencing a state Var enables state. a2.add_page(rx.box(rx.text(GenState.value)), route="/") a2._compile_page("index") - assert a2.state is not None + assert a2._state is not None a3 = App() - assert a3.state is None + assert a3._state is None # Referencing router enables state. a3.add_page(rx.box(rx.text(State.router.page.full_path)), route="/") a3._compile_page("index") - assert a3.state is not None + assert a3._state is not None a4 = App() - assert a4.state is None + assert a4._state is None a4.add_page(rx.box(rx.button("Click", on_click=rx.console_log(""))), route="/") - assert a4.state is None + assert a4._state is None a4.add_page( rx.box(rx.button("Click", on_click=DynamicState.on_counter)), route="/page2" ) a4._compile_page("page2") - assert a4.state is not None + assert a4._state is not None def test_raise_on_state(): """Test that the state is set.""" # state kwargs is deprecated, we just make sure the app is created anyway. - _app = App(state=State) - assert _app.state is not None - assert issubclass(_app.state, State) + _app = App(_state=State) + assert _app._state is not None + assert issubclass(_app._state, State) def test_call_app(): @@ -1448,11 +1468,11 @@ def test_generate_component(): "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,27 +1487,27 @@ def test_add_page_component_returning_tuple(): 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") - fragment_wrapper = app.pages["index"].children[0] + fragment_wrapper = app._pages["index"].children[0] 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] + 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 +1545,7 @@ def test_app_with_transpile_packages(compilable_app: tuple[App, Path], export: b 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 == [ @@ -1557,7 +1577,17 @@ def test_app_with_valid_var_dependencies(compilable_app: tuple[App, Path]): def bar(self) -> str: return "bar" - app.state = ValidDepState + class Child1(ValidDepState): + @computed_var(deps=["base", ValidDepState.bar]) + def other(self) -> str: + return "other" + + class Child2(ValidDepState): + @computed_var(deps=["base", Child1.other]) + def other(self) -> str: + return "other" + + app._state = ValidDepState app._compile() @@ -1569,7 +1599,7 @@ def test_app_with_invalid_var_dependencies(compilable_app: tuple[App, Path]): def bar(self) -> str: return "bar" - app.state = InvalidDepState + app._state = InvalidDepState with pytest.raises(exceptions.VarDependencyError): app._compile() diff --git a/tests/units/test_config.py b/tests/units/test_config.py index e5d4622bd..88d8b5f2f 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -21,7 +21,7 @@ from reflex.constants import Endpoint, Env 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 d7e993efa..afcfda504 100644 --- a/tests/units/test_event.py +++ b/tests/units/test_event.py @@ -3,6 +3,7 @@ from typing import Callable, List import pytest import reflex as rx +from reflex.constants.compiler import Hooks, Imports from reflex.event import ( Event, EventChain, @@ -14,7 +15,7 @@ from reflex.event import ( ) from reflex.state import BaseState from reflex.utils import format -from reflex.vars.base import Field, LiteralVar, Var, field +from reflex.vars.base import Field, LiteralVar, Var, VarData, field def make_var(value) -> Var: @@ -72,7 +73,7 @@ def test_call_event_handler(): ) # 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 +81,7 @@ def test_call_event_handler(): 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 +95,7 @@ def test_call_event_handler(): 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(): @@ -199,16 +200,15 @@ def test_event_redirect(input, output): input: The input for running the test. output: The expected output to validate the test. """ - path, external, replace = input + path, is_external, replace = input kwargs = {} - if external is not None: - kwargs["external"] = external + if is_external is not None: + kwargs["is_external"] = is_external if replace is not None: kwargs["replace"] = replace spec = event.redirect(path, **kwargs) assert isinstance(spec, EventSpec) assert spec.handler.fn.__qualname__ == "_redirect" - assert format.format_event(spec) == output @@ -417,7 +417,7 @@ def test_event_actions_on_state(): 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 @@ -444,9 +444,28 @@ def test_event_var_data(): return (value,) # Ensure chain carries _var_data - chain_var = Var.create(EventChain(events=[S.s(S.x)], args_spec=_args_spec)) + chain_var = Var.create( + EventChain( + events=[S.s(S.x)], + args_spec=_args_spec, + invocation=rx.vars.FunctionStringVar.create(""), + ) + ) assert chain_var._get_all_var_data() == S.x._get_all_var_data() + chain_var_data = Var.create( + EventChain( + events=[], + args_spec=_args_spec, + ) + )._get_all_var_data() + assert chain_var_data is not None + + assert chain_var_data == VarData( + imports=Imports.EVENTS, + hooks={Hooks.EVENTS: None}, + ) + def test_event_bound_method() -> None: class S(BaseState): diff --git a/tests/units/test_health_endpoint.py b/tests/units/test_health_endpoint.py index 6d12d79d6..5b3aedc00 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 0a83f39ec..b17538248 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 @@ def test_automigration( 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 @@ def test_automigration( 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 @@ def test_automigration( 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 @@ def test_automigration( # 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 @@ def test_automigration( 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 90afe0963..4723d8648 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -1,20 +1,28 @@ import json import re +import shutil import tempfile +from pathlib import Path from unittest.mock import Mock, mock_open import pytest +from typer.testing import CliRunner from reflex import constants from reflex.config import Config +from reflex.reflex import cli +from reflex.testing import chdir from reflex.utils.prerequisites import ( CpuInfo, _update_next_config, cached_procedure, get_cpu_info, initialize_requirements_txt, + rename_imports_and_app_name, ) +runner = CliRunner() + @pytest.mark.parametrize( "config, export, expected_output", @@ -24,7 +32,7 @@ from reflex.utils.prerequisites import ( app_name="test", ), False, - 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', + 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60};', ), ( Config( @@ -32,7 +40,7 @@ from reflex.utils.prerequisites import ( static_page_generation_timeout=30, ), False, - 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 30};', + 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 30};', ), ( Config( @@ -40,7 +48,7 @@ from reflex.utils.prerequisites import ( next_compression=False, ), False, - 'module.exports = {basePath: "", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', + 'module.exports = {basePath: "", compress: false, trailingSlash: true, staticPageGenerationTimeout: 60};', ), ( Config( @@ -48,7 +56,7 @@ from reflex.utils.prerequisites import ( frontend_path="/test", ), False, - 'module.exports = {basePath: "/test", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', + 'module.exports = {basePath: "/test", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60};', ), ( Config( @@ -57,14 +65,14 @@ from reflex.utils.prerequisites import ( next_compression=False, ), False, - 'module.exports = {basePath: "/test", compress: false, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60};', + 'module.exports = {basePath: "/test", compress: false, trailingSlash: true, staticPageGenerationTimeout: 60};', ), ( Config( app_name="test", ), True, - 'module.exports = {basePath: "", compress: true, reactStrictMode: true, trailingSlash: true, staticPageGenerationTimeout: 60, output: "export", distDir: "_static"};', + 'module.exports = {basePath: "", compress: true, trailingSlash: true, staticPageGenerationTimeout: 60, output: "export", distDir: "_static"};', ), ], ) @@ -92,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 @@ -224,3 +232,156 @@ def test_get_cpu_info(): for attr in ("manufacturer_id", "model_name", "address_width"): value = getattr(cpu_info, attr) assert value.strip() if attr != "address_width" else value + + +@pytest.fixture +def temp_directory(): + temp_dir = tempfile.mkdtemp() + yield Path(temp_dir) + shutil.rmtree(temp_dir) + + +@pytest.mark.parametrize( + "config_code,expected", + [ + ("rx.Config(app_name='old_name')", 'rx.Config(app_name="new_name")'), + ('rx.Config(app_name="old_name")', 'rx.Config(app_name="new_name")'), + ("rx.Config('old_name')", 'rx.Config("new_name")'), + ('rx.Config("old_name")', 'rx.Config("new_name")'), + ], +) +def test_rename_imports_and_app_name(temp_directory, config_code, expected): + file_path = temp_directory / "rxconfig.py" + content = f""" +config = {config_code} +""" + file_path.write_text(content) + + rename_imports_and_app_name(file_path, "old_name", "new_name") + + updated_content = file_path.read_text() + expected_content = f""" +config = {expected} +""" + assert updated_content == expected_content + + +def test_regex_edge_cases(temp_directory): + file_path = temp_directory / "example.py" + content = """ +from old_name.module import something +import old_name +from old_name import something_else as alias +from old_name +""" + file_path.write_text(content) + + rename_imports_and_app_name(file_path, "old_name", "new_name") + + updated_content = file_path.read_text() + expected_content = """ +from new_name.module import something +import new_name +from new_name import something_else as alias +from new_name +""" + assert updated_content == expected_content + + +def test_cli_rename_command(temp_directory): + foo_dir = temp_directory / "foo" + foo_dir.mkdir() + (foo_dir / "__init__").touch() + (foo_dir / ".web").mkdir() + (foo_dir / "assets").mkdir() + (foo_dir / "foo").mkdir() + (foo_dir / "foo" / "__init__.py").touch() + (foo_dir / "rxconfig.py").touch() + (foo_dir / "rxconfig.py").write_text( + """ +import reflex as rx + +config = rx.Config( + app_name="foo", +) +""" + ) + (foo_dir / "foo" / "components").mkdir() + (foo_dir / "foo" / "components" / "__init__.py").touch() + (foo_dir / "foo" / "components" / "base.py").touch() + (foo_dir / "foo" / "components" / "views.py").touch() + (foo_dir / "foo" / "components" / "base.py").write_text( + """ +import reflex as rx +from foo.components import views +from foo.components.views import * +from .base import * + +def random_component(): + return rx.fragment() +""" + ) + (foo_dir / "foo" / "foo.py").touch() + (foo_dir / "foo" / "foo.py").write_text( + """ +import reflex as rx +import foo.components.base +from foo.components.base import random_component + +class State(rx.State): + pass + + +def index(): + return rx.text("Hello, World!") + +app = rx.App() +app.add_page(index) +""" + ) + + with chdir(temp_directory / "foo"): + result = runner.invoke(cli, ["rename", "bar"]) + + assert result.exit_code == 0 + assert (foo_dir / "rxconfig.py").read_text() == ( + """ +import reflex as rx + +config = rx.Config( + app_name="bar", +) +""" + ) + assert (foo_dir / "bar").exists() + assert not (foo_dir / "foo").exists() + assert (foo_dir / "bar" / "components" / "base.py").read_text() == ( + """ +import reflex as rx +from bar.components import views +from bar.components.views import * +from .base import * + +def random_component(): + return rx.fragment() +""" + ) + assert (foo_dir / "bar" / "bar.py").exists() + assert not (foo_dir / "bar" / "foo.py").exists() + assert (foo_dir / "bar" / "bar.py").read_text() == ( + """ +import reflex as rx +import bar.components.base +from bar.components.base import random_component + +class State(rx.State): + pass + + +def index(): + return rx.text("Hello, World!") + +app = rx.App() +app.add_page(index) +""" + ) diff --git a/tests/units/test_route.py b/tests/units/test_route.py index 851c9cf35..62f1788d3 100644 --- a/tests/units/test_route.py +++ b/tests/units/test_route.py @@ -89,7 +89,7 @@ def app(): ], ) def test_check_routes_conflict_invalid(mocker, app, route1, route2): - mocker.patch.object(app, "pages", {route1: []}) + mocker.patch.object(app, "_pages", {route1: []}) with pytest.raises(ValueError): app._check_routes_conflict(route2) @@ -117,6 +117,6 @@ def test_check_routes_conflict_invalid(mocker, app, route1, route2): ], ) def test_check_routes_conflict_valid(mocker, app, route1, route2): - mocker.patch.object(app, "pages", {route1: []}) + mocker.patch.object(app, "_pages", {route1: []}) # test that running this does not throw an error. app._check_routes_conflict(route2) diff --git a/tests/units/test_sqlalchemy.py b/tests/units/test_sqlalchemy.py index 23e315785..4434f5ee1 100644 --- a/tests/units/test_sqlalchemy.py +++ b/tests/units/test_sqlalchemy.py @@ -59,7 +59,7 @@ def test_automigration( 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 @@ def test_automigration( 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 @@ def test_automigration( 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 @@ def test_automigration( # 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 19f3e4239..44c3f60b7 100644 --- a/tests/units/test_state.py +++ b/tests/units/test_state.py @@ -14,6 +14,7 @@ from typing import ( Any, AsyncGenerator, Callable, + ClassVar, Dict, List, Optional, @@ -241,7 +242,7 @@ def test_state() -> TestState: Returns: A test state. """ - return TestState() # type: ignore + return TestState() # pyright: ignore [reportCallIssue] @pytest.fixture @@ -431,10 +432,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 +555,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() @@ -789,17 +790,16 @@ async def test_process_event_simple(test_state): assert test_state.num1 == 0 event = Event(token="t", name="set_num1", payload={"value": 69}) - update = await test_state._process(event).__anext__() + async for update in test_state._process(event): + # The event should update the value. + assert test_state.num1 == 69 - # The event should update the value. - assert test_state.num1 == 69 - - # The delta should contain the changes, including computed vars. - assert update.delta == { - TestState.get_full_name(): {"num1": 69, "sum": 72.14}, - GrandchildState3.get_full_name(): {"computed": ""}, - } - assert update.events == [] + # The delta should contain the changes, including computed vars. + assert update.delta == { + TestState.get_full_name(): {"num1": 69, "sum": 72.14}, + GrandchildState3.get_full_name(): {"computed": ""}, + } + assert update.events == [] @pytest.mark.asyncio @@ -819,15 +819,15 @@ async def test_process_event_substate(test_state, child_state, grandchild_state) name=f"{ChildState.get_name()}.change_both", payload={"value": "hi", "count": 12}, ) - update = await test_state._process(event).__anext__() - assert child_state.value == "HI" - assert child_state.count == 24 - assert update.delta == { - # TestState.get_full_name(): {"sum": 3.14, "upper": ""}, - ChildState.get_full_name(): {"value": "HI", "count": 24}, - GrandchildState3.get_full_name(): {"computed": ""}, - } - test_state._clean() + async for update in test_state._process(event): + assert child_state.value == "HI" + assert child_state.count == 24 + assert update.delta == { + # TestState.get_full_name(): {"sum": 3.14, "upper": ""}, + ChildState.get_full_name(): {"value": "HI", "count": 24}, + GrandchildState3.get_full_name(): {"computed": ""}, + } + test_state._clean() # Test with the granchild state. assert grandchild_state.value2 == "" @@ -836,19 +836,19 @@ async def test_process_event_substate(test_state, child_state, grandchild_state) name=f"{GrandchildState.get_full_name()}.set_value2", payload={"value": "new"}, ) - update = await test_state._process(event).__anext__() - assert grandchild_state.value2 == "new" - assert update.delta == { - # TestState.get_full_name(): {"sum": 3.14, "upper": ""}, - GrandchildState.get_full_name(): {"value2": "new"}, - GrandchildState3.get_full_name(): {"computed": ""}, - } + async for update in test_state._process(event): + assert grandchild_state.value2 == "new" + assert update.delta == { + # TestState.get_full_name(): {"sum": 3.14, "upper": ""}, + GrandchildState.get_full_name(): {"value2": "new"}, + GrandchildState3.get_full_name(): {"computed": ""}, + } @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 @@ def test_add_var(): 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 @@ def test_add_var(): 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 @@ class InterdependentState(BaseState): Returns: ComputedVar v1x2 multiplied by 2 """ - return self.v1x2 * 2 # type: ignore + return self.v1x2 * 2 @rx.var def _v3(self) -> int: @@ -1144,7 +1144,7 @@ def test_child_state(): class ChildState(MainState): @computed_var - def rendered_var(self): + def rendered_var(self) -> int: return self.v ms = MainState() @@ -1170,13 +1170,17 @@ def test_conditional_computed_vars(): ms = MainState() # Initially there are no dirty computed vars. - assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"} - assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"} - assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"} + assert ms._dirty_computed_vars(from_vars={"flag"}) == { + (MainState.get_full_name(), "rendered_var") + } + assert ms._dirty_computed_vars(from_vars={"t2"}) == { + (MainState.get_full_name(), "rendered_var") + } + assert ms._dirty_computed_vars(from_vars={"t1"}) == { + (MainState.get_full_name(), "rendered_var") + } assert ms.computed_vars["rendered_var"]._deps(objclass=MainState) == { - "flag", - "t1", - "t2", + MainState.get_full_name(): {"flag", "t1", "t2"} } @@ -1270,7 +1274,7 @@ def test_computed_var_cached_depends_on_non_cached(): @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 +1317,7 @@ def test_computed_var_depends_on_parent_non_cached(): 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,13 +1369,16 @@ def test_cached_var_depends_on_event_handler(use_partial: bool): 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) s = HandlerState() - assert "cached_x_side_effect" in s._computed_var_dependencies["x"] + assert ( + HandlerState.get_full_name(), + "cached_x_side_effect", + ) in s._var_dependencies["x"] assert s.cached_x_side_effect == 1 assert s.x == 43 s.handler() @@ -1421,7 +1428,7 @@ def test_computed_var_dependencies(): return self.testprop @rx.var - def comp_w(self): + def comp_w(self) -> Callable[[], int]: """Nested lambda. Returns: @@ -1430,7 +1437,7 @@ def test_computed_var_dependencies(): return lambda: self.w @rx.var - def comp_x(self): + def comp_x(self) -> Callable[[], int]: """Nested function. Returns: @@ -1443,7 +1450,7 @@ def test_computed_var_dependencies(): return _ @rx.var - def comp_y(self) -> List[int]: + def comp_y(self) -> list[int]: """Comprehension iterating over attribute. Returns: @@ -1461,15 +1468,15 @@ def test_computed_var_dependencies(): return [z in self._z for z in range(5)] cs = ComputedState() - assert cs._computed_var_dependencies["v"] == { - "comp_v", - "comp_v_backend", - "comp_v_via_property", + assert cs._var_dependencies["v"] == { + (ComputedState.get_full_name(), "comp_v"), + (ComputedState.get_full_name(), "comp_v_backend"), + (ComputedState.get_full_name(), "comp_v_via_property"), } - assert cs._computed_var_dependencies["w"] == {"comp_w"} - assert cs._computed_var_dependencies["x"] == {"comp_x"} - assert cs._computed_var_dependencies["y"] == {"comp_y"} - assert cs._computed_var_dependencies["_z"] == {"comp_z"} + assert cs._var_dependencies["w"] == {(ComputedState.get_full_name(), "comp_w")} + assert cs._var_dependencies["x"] == {(ComputedState.get_full_name(), "comp_x")} + assert cs._var_dependencies["y"] == {(ComputedState.get_full_name(), "comp_y")} + assert cs._var_dependencies["_z"] == {(ComputedState.get_full_name(), "comp_z")} def test_backend_method(): @@ -1616,7 +1623,7 @@ async def test_state_with_invalid_yield(capsys, mock_app): id="backend_error", position="top-center", style={"width": "500px"}, - ) # type: ignore + ) # pyright: ignore [reportCallIssue, reportArgumentType] ], token="", ) @@ -1907,13 +1914,13 @@ def mock_app_simple(monkeypatch) -> rx.App: Returns: The app, after mocking out prerequisites.get_app() """ - app = App(state=TestState) + app = App(_state=TestState) app_module = Mock() setattr(app_module, CompileVars.APP, app) - app.state = TestState - app.event_namespace.emit = CopyingAsyncMock() # type: ignore + app._state = TestState + app.event_namespace.emit = CopyingAsyncMock() # pyright: ignore [reportOptionalMemberAccess] def _mock_get_app(*args, **kwargs): return app_module @@ -2022,8 +2029,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={ @@ -2153,8 +2160,8 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): token: A token. """ router_data = {"query": {}} - mock_app.state_manager.state = mock_app.state = BackgroundTaskState - async for update in rx.app.process( # type: ignore + mock_app.state_manager.state = mock_app._state = BackgroundTaskState + async for update in rx.app.process( mock_app, Event( token=token, @@ -2171,10 +2178,10 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): # wait for the coroutine to start await asyncio.sleep(0.5 if CI else 0.1) - assert len(mock_app.background_tasks) == 1 + 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, @@ -2203,9 +2210,9 @@ async def test_background_task_no_block(mock_app: rx.App, token: str): ) # Explicit wait for background tasks - for task in tuple(mock_app.background_tasks): + for task in tuple(mock_app._background_tasks): await task - assert not mock_app.background_tasks + assert not mock_app._background_tasks exp_order = [ "background_task:start", @@ -2224,7 +2231,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 +2246,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 +2256,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 +2267,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, @@ -2280,8 +2287,8 @@ async def test_background_task_reset(mock_app: rx.App, token: str): token: A token. """ router_data = {"query": {}} - mock_app.state_manager.state = mock_app.state = BackgroundTaskState - async for update in rx.app.process( # type: ignore + mock_app.state_manager.state = mock_app._state = BackgroundTaskState + async for update in rx.app.process( mock_app, Event( token=token, @@ -2297,9 +2304,9 @@ async def test_background_task_reset(mock_app: rx.App, token: str): assert update == StateUpdate() # Explicit wait for background tasks - for task in tuple(mock_app.background_tasks): + for task in tuple(mock_app._background_tasks): await task - assert not mock_app.background_tasks + assert not mock_app._background_tasks assert ( await mock_app.state_manager.get_state( @@ -2623,10 +2630,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 +2671,21 @@ def test_reset_with_mutables(): 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 +2747,30 @@ def test_state_union_optional(): 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(): @@ -2884,7 +2891,7 @@ async def test_preprocess(app_module_mock, token, test_state, expected, mocker): "reflex.state.State.class_subclasses", {test_state, OnLoadInternalState} ) app = app_module_mock.app = App( - state=State, load_events={"index": [test_state.test_handler]} + _state=State, _load_events={"index": [test_state.test_handler]} ) async with app.state_manager.modify_state(_substate_key(token, State)) as state: state.router_data = {"simulate": "hydrate"} @@ -2909,10 +2916,10 @@ async def test_preprocess(app_module_mock, token, test_state, expected, mocker): events = updates[0].events assert len(events) == 2 - assert (await state._process(events[0]).__anext__()).delta == { - test_state.get_full_name(): {"num": 1} - } - assert (await state._process(events[1]).__anext__()).delta == exp_is_hydrated(state) + async for update in state._process(events[0]): + assert update.delta == {test_state.get_full_name(): {"num": 1}} + async for update in state._process(events[1]): + assert update.delta == exp_is_hydrated(state) if isinstance(app.state_manager, StateManagerRedis): await app.state_manager.close() @@ -2931,8 +2938,8 @@ async def test_preprocess_multiple_load_events(app_module_mock, token, mocker): "reflex.state.State.class_subclasses", {OnLoadState, OnLoadInternalState} ) app = app_module_mock.app = App( - state=State, - load_events={"index": [OnLoadState.test_handler, OnLoadState.test_handler]}, + _state=State, + _load_events={"index": [OnLoadState.test_handler, OnLoadState.test_handler]}, ) async with app.state_manager.modify_state(_substate_key(token, State)) as state: state.router_data = {"simulate": "hydrate"} @@ -2957,13 +2964,12 @@ async def test_preprocess_multiple_load_events(app_module_mock, token, mocker): events = updates[0].events assert len(events) == 3 - assert (await state._process(events[0]).__anext__()).delta == { - OnLoadState.get_full_name(): {"num": 1} - } - assert (await state._process(events[1]).__anext__()).delta == { - OnLoadState.get_full_name(): {"num": 2} - } - assert (await state._process(events[2]).__anext__()).delta == exp_is_hydrated(state) + async for update in state._process(events[0]): + assert update.delta == {OnLoadState.get_full_name(): {"num": 1}} + async for update in state._process(events[1]): + assert update.delta == {OnLoadState.get_full_name(): {"num": 2}} + async for update in state._process(events[2]): + assert update.delta == exp_is_hydrated(state) if isinstance(app.state_manager, StateManagerRedis): await app.state_manager.close() @@ -2977,7 +2983,7 @@ async def test_get_state(mock_app: rx.App, token: str): mock_app: An app that will be returned by `get_app()` token: A token. """ - mock_app.state_manager.state = mock_app.state = TestState + mock_app.state_manager.state = mock_app._state = TestState # Get instance of ChildState2. test_state = await mock_app.state_manager.get_state( @@ -3128,7 +3134,7 @@ async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str): child3_var: int = 0 @rx.var(cache=False) - def v(self): + def v(self) -> None: pass class Grandchild3(Child3): @@ -3147,7 +3153,7 @@ async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str): pass - mock_app.state_manager.state = mock_app.state = Parent + mock_app.state_manager.state = mock_app._state = Parent # Get the top level state via unconnected sibling. root = await mock_app.state_manager.get_state(_substate_key(token, Child)) @@ -3182,7 +3188,7 @@ async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str): RxState = State -def test_potentially_dirty_substates(): +def test_potentially_dirty_states(): """Test that potentially_dirty_substates returns the correct substates. Even if the name "State" is shadowed, it should still work correctly. @@ -3198,13 +3204,19 @@ def test_potentially_dirty_substates(): def bar(self) -> str: return "" - assert RxState._potentially_dirty_substates() == set() - assert State._potentially_dirty_substates() == set() - assert C1._potentially_dirty_substates() == set() + assert RxState._get_potentially_dirty_states() == set() + assert State._get_potentially_dirty_states() == set() + assert C1._get_potentially_dirty_states() == set() -def test_router_var_dep() -> None: - """Test that router var dependencies are correctly tracked.""" +@pytest.mark.asyncio +async def test_router_var_dep(state_manager: StateManager, token: str) -> None: + """Test that router var dependencies are correctly tracked. + + Args: + state_manager: A state manager. + token: A token. + """ class RouterVarParentState(State): """A parent state for testing router var dependency.""" @@ -3221,30 +3233,27 @@ def test_router_var_dep() -> None: foo = RouterVarDepState.computed_vars["foo"] State._init_var_dependency_dicts() - assert foo._deps(objclass=RouterVarDepState) == {"router"} - assert RouterVarParentState._potentially_dirty_substates() == {RouterVarDepState} - assert RouterVarParentState._substate_var_dependencies == { - "router": {RouterVarDepState.get_name()} - } - assert RouterVarDepState._computed_var_dependencies == { - "router": {"foo"}, + assert foo._deps(objclass=RouterVarDepState) == { + RouterVarDepState.get_full_name(): {"router"} } + assert (RouterVarDepState.get_full_name(), "foo") in State._var_dependencies[ + "router" + ] - rx_state = State() - parent_state = RouterVarParentState() - state = RouterVarDepState() - - # link states - rx_state.substates = {RouterVarParentState.get_name(): parent_state} - parent_state.parent_state = rx_state - state.parent_state = parent_state - parent_state.substates = {RouterVarDepState.get_name(): state} + # Get state from state manager. + state_manager.state = State + rx_state = await state_manager.get_state(_substate_key(token, State)) + assert RouterVarParentState.get_name() in rx_state.substates + parent_state = rx_state.substates[RouterVarParentState.get_name()] + assert RouterVarDepState.get_name() in parent_state.substates + state = parent_state.substates[RouterVarDepState.get_name()] assert state.dirty_vars == set() # Reassign router var state.router = state.router - assert state.dirty_vars == {"foo", "router"} + assert rx_state.dirty_vars == {"router"} + assert state.dirty_vars == {"foo"} assert parent_state.dirty_substates == {RouterVarDepState.get_name()} @@ -3360,9 +3369,9 @@ config = rx.Config( 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 +3450,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 +3470,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 +3490,8 @@ def test_assignment_to_undeclared_vars(): 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 +3553,7 @@ def test_fallback_pickle(): _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 +3564,14 @@ def test_fallback_pickle(): 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 +3746,7 @@ class UpcastState(rx.State): 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 @@ -3803,3 +3812,128 @@ async def test_get_var_value(state_manager: StateManager, substate_token: str): # Generic Var with no state with pytest.raises(UnretrievableVarValueError): await state.get_var_value(rx.Var("undefined")) + + +@pytest.mark.asyncio +async def test_async_computed_var_get_state(mock_app: rx.App, token: str): + """A test where an async computed var depends on a var in another state. + + Args: + mock_app: An app that will be returned by `get_app()` + token: A token. + """ + + class Parent(BaseState): + """A root state like rx.State.""" + + parent_var: int = 0 + + class Child2(Parent): + """An unconnected child state.""" + + pass + + class Child3(Parent): + """A child state with a computed var causing it to be pre-fetched. + + If child3_var gets set to a value, and `get_state` erroneously + re-fetches it from redis, the value will be lost. + """ + + child3_var: int = 0 + + @rx.var(cache=True) + def v(self) -> int: + return self.child3_var + + class Child(Parent): + """A state simulating UpdateVarsInternalState.""" + + @rx.var(cache=True) + async def v(self) -> int: + p = await self.get_state(Parent) + child3 = await self.get_state(Child3) + return child3.child3_var + p.parent_var + + mock_app.state_manager.state = mock_app._state = Parent + + # Get the top level state via unconnected sibling. + root = await mock_app.state_manager.get_state(_substate_key(token, Child)) + # Set value in parent_var to assert it does not get refetched later. + root.parent_var = 1 + + if isinstance(mock_app.state_manager, StateManagerRedis): + # When redis is used, only states with uncached computed vars are pre-fetched. + assert Child2.get_name() not in root.substates + assert Child3.get_name() not in root.substates + + # Get the unconnected sibling state, which will be used to `get_state` other instances. + child = root.get_substate(Child.get_full_name().split(".")) + + # Get an uncached child state. + child2 = await child.get_state(Child2) + assert child2.parent_var == 1 + + # Set value on already-cached Child3 state (prefetched because it has a Computed Var). + child3 = await child.get_state(Child3) + child3.child3_var = 1 + + assert await child.v == 2 + assert await child.v == 2 + root.parent_var = 2 + assert await child.v == 3 + + +class Table(rx.ComponentState): + """A table state.""" + + data: ClassVar[Var] + + @rx.var(cache=True, auto_deps=False) + async def rows(self) -> List[Dict[str, Any]]: + """Computed var over the given rows. + + Returns: + The data rows. + """ + return await self.get_var_value(self.data) + + @classmethod + def get_component(cls, data: Var) -> rx.Component: + """Get the component for the table. + + Args: + data: The data var. + + Returns: + The component. + """ + cls.data = data + cls.computed_vars["rows"].add_dependency(cls, data) + return rx.foreach(data, lambda d: rx.text(d.to_string())) + + +@pytest.mark.asyncio +async def test_async_computed_var_get_var_value(mock_app: rx.App, token: str): + """A test where an async computed var depends on a var in another state. + + Args: + mock_app: An app that will be returned by `get_app()` + token: A token. + """ + + class OtherState(rx.State): + """A state with a var.""" + + data: List[Dict[str, Any]] = [{"foo": "bar"}] + + mock_app.state_manager.state = mock_app._state = rx.State + comp = Table.create(data=OtherState.data) + state = await mock_app.state_manager.get_state(_substate_key(token, OtherState)) + other_state = await state.get_state(OtherState) + assert comp.State is not None + comp_state = await state.get_state(comp.State) + assert comp_state.dirty_vars == set() + + other_state.data.append({"foo": "baz"}) + assert "rows" in comp_state.dirty_vars diff --git a/tests/units/test_state_tree.py b/tests/units/test_state_tree.py index 6fe828819..70ef71cb8 100644 --- a/tests/units/test_state_tree.py +++ b/tests/units/test_state_tree.py @@ -222,7 +222,7 @@ async def state_manager_redis( Yields: A state manager instance """ - app_module_mock.app = rx.App(state=Root) + app_module_mock.app = rx.App(_state=Root) state_manager = app_module_mock.app.state_manager if not isinstance(state_manager, StateManagerRedis): diff --git a/tests/units/test_style.py b/tests/units/test_style.py index e1d652798..e8ff5bd01 100644 --- a/tests/units/test_style.py +++ b/tests/units/test_style.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Dict +from typing import Any, Mapping import pytest @@ -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) @@ -379,7 +379,7 @@ class StyleState(rx.State): { "css": Var( _js_expr=f'({{ ["color"] : ("dark"+{StyleState.color}) }})' - ).to(Dict[str, str]) + ).to(Mapping[str, str]) }, ), ( @@ -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( @@ -541,3 +541,7 @@ def test_style_update_with_var_data(): assert s2._var_data is not None assert "const red = true" in s2._var_data.hooks assert "const blue = true" in s2._var_data.hooks + + s3 = s1 | s2 + assert s3._var_data is not None + assert "_varData" not in s3 diff --git a/tests/units/test_testing.py b/tests/units/test_testing.py index 83a03ad83..8c8f1461b 100644 --- a/tests/units/test_testing.py +++ b/tests/units/test_testing.py @@ -23,7 +23,7 @@ def test_app_harness(tmp_path): class State(rx.State): pass - app = rx.App(state=State) + app = rx.App(_state=State) app.add_page(lambda: rx.text("Basic App"), route="/", title="index") app._compile() diff --git a/tests/units/test_var.py b/tests/units/test_var.py index 6ad82a761..a72242814 100644 --- a/tests/units/test_var.py +++ b/tests/units/test_var.py @@ -1,8 +1,7 @@ import json import math -import sys import typing -from typing import Dict, List, Optional, Set, Tuple, Union, cast +from typing import Dict, List, Mapping, Optional, Set, Tuple, Union, cast import pytest from pandas import DataFrame @@ -11,7 +10,10 @@ import reflex as rx from reflex.base import Base from reflex.constants.base import REFLEX_VAR_CLOSING_TAG, REFLEX_VAR_OPENING_TAG from reflex.state import BaseState -from reflex.utils.exceptions import PrimitiveUnserializableToJSON +from reflex.utils.exceptions import ( + PrimitiveUnserializableToJSONError, + UntypedComputedVarError, +) from reflex.utils.imports import ImportVar from reflex.vars import VarData from reflex.vars.base import ( @@ -185,6 +187,7 @@ def ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar): "state.local", "local2", ], + strict=True, ), ) def test_full_name(prop, expected): @@ -202,6 +205,7 @@ def test_full_name(prop, expected): zip( test_vars, ["prop1", "key", "state.value", "state.local", "local2"], + strict=True, ), ) def test_str(prop, expected): @@ -248,6 +252,7 @@ def test_default_value(prop: Var, expected): "state.set_local", "set_local2", ], + strict=True, ), ) def test_get_setter(prop: Var, expected): @@ -270,7 +275,7 @@ def test_get_setter(prop: Var, expected): ([1, 2, 3], Var(_js_expr="[1, 2, 3]", _var_type=List[int])), ( {"a": 1, "b": 2}, - Var(_js_expr='({ ["a"] : 1, ["b"] : 2 })', _var_type=Dict[str, int]), + Var(_js_expr='({ ["a"] : 1, ["b"] : 2 })', _var_type=Mapping[str, int]), ), ], ) @@ -282,7 +287,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(): @@ -416,19 +421,13 @@ class Bar(rx.Base): @pytest.mark.parametrize( ("var", "var_type"), - ( - [ - (Var(_js_expr="", _var_type=Foo | Bar).guess_type(), Foo | Bar), - (Var(_js_expr="", _var_type=Foo | Bar).guess_type().bar, Union[int, str]), - ] - if sys.version_info >= (3, 10) - else [] - ) - + [ - (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type(), Union[Foo, Bar]), - (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().baz, str), + [ + (Var(_js_expr="").to(Foo | Bar), Foo | Bar), + (Var(_js_expr="").to(Foo | Bar).bar, Union[int, str]), + (Var(_js_expr="").to(Union[Foo, Bar]), Union[Foo, Bar]), + (Var(_js_expr="").to(Union[Foo, Bar]).baz, str), ( - Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().foo, + Var(_js_expr="").to(Union[Foo, Bar]).foo, Union[int, None], ), ], @@ -804,7 +803,7 @@ def test_shadow_computed_var_error(request: pytest.FixtureRequest, fixture: str) request: Fixture Request. fixture: The state fixture. """ - with pytest.raises(NameError): + with pytest.raises(UntypedComputedVarError): state = request.getfixturevalue(fixture) state.var_without_annotation.foo @@ -1058,7 +1057,7 @@ def test_inf_and_nan(var, expected_js): assert str(var) == expected_js assert isinstance(var, NumberVar) assert isinstance(var, LiteralVar) - with pytest.raises(PrimitiveUnserializableToJSON): + with pytest.raises(PrimitiveUnserializableToJSONError): var.json() @@ -1070,19 +1069,19 @@ def test_array_operations(): assert str(array_var.reverse()) == "[1, 2, 3, 4, 5].slice().reverse()" assert ( str(ArrayVar.range(10)) - == "Array.from({ length: (10 - 0) / 1 }, (_, i) => 0 + i * 1)" + == "Array.from({ length: Math.ceil((10 - 0) / 1) }, (_, i) => 0 + i * 1)" ) assert ( str(ArrayVar.range(1, 10)) - == "Array.from({ length: (10 - 1) / 1 }, (_, i) => 1 + i * 1)" + == "Array.from({ length: Math.ceil((10 - 1) / 1) }, (_, i) => 1 + i * 1)" ) assert ( str(ArrayVar.range(1, 10, 2)) - == "Array.from({ length: (10 - 1) / 2 }, (_, i) => 1 + i * 2)" + == "Array.from({ length: Math.ceil((10 - 1) / 2) }, (_, i) => 1 + i * 2)" ) assert ( str(ArrayVar.range(1, 10, -1)) - == "Array.from({ length: (10 - 1) / -1 }, (_, i) => 1 + i * -1)" + == "Array.from({ length: Math.ceil((10 - 1) / -1) }, (_, i) => 1 + i * -1)" ) @@ -1127,7 +1126,7 @@ def test_var_component(): 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) @@ -1139,15 +1138,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"])' ) @@ -1156,7 +1155,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] ) @@ -1352,7 +1351,7 @@ def test_unsupported_types_for_contains(var: Var): var: The base var. """ with pytest.raises(TypeError) as err: - assert var.contains(1) + assert var.contains(1) # pyright: ignore [reportAttributeAccessIssue] assert ( err.value.args[0] == f"Var of type {var._var_type} does not support contains check." @@ -1382,7 +1381,7 @@ def test_unsupported_types_for_string_contains(other): def test_unsupported_default_contains(): with pytest.raises(TypeError) as err: - assert 1 in Var(_js_expr="var", _var_type=str).guess_type() + assert 1 in Var(_js_expr="var", _var_type=str).guess_type() # pyright: ignore [reportOperatorIssue] assert ( err.value.args[0] == "'in' operator not supported for Var types, use Var.contains() instead." @@ -1808,9 +1807,9 @@ def cv_fget(state: BaseState) -> int: @pytest.mark.parametrize( "deps,expected", [ - (["a"], {"a"}), - (["b"], {"b"}), - ([ComputedVar(fget=cv_fget)], {"cv_fget"}), + (["a"], {None: {"a"}}), + (["b"], {None: {"b"}}), + ([ComputedVar(fget=cv_fget)], {None: {"cv_fget"}}), ], ) def test_computed_var_deps(deps: List[Union[str, Var]], expected: Set[str]): @@ -1856,3 +1855,41 @@ def test_to_string_operation(): single_var = Var.create(Email()) assert single_var._var_type == Email + + +@pytest.mark.asyncio +async def test_async_computed_var(): + side_effect_counter = 0 + + class AsyncComputedVarState(BaseState): + v: int = 1 + + @computed_var(cache=True) + async def async_computed_var(self) -> int: + nonlocal side_effect_counter + side_effect_counter += 1 + return self.v + 1 + + my_state = AsyncComputedVarState() + assert await my_state.async_computed_var == 2 + assert await my_state.async_computed_var == 2 + my_state.v = 2 + assert await my_state.async_computed_var == 3 + assert await my_state.async_computed_var == 3 + assert side_effect_counter == 2 + + +def test_var_data_hooks(): + var_data_str = VarData(hooks="what") + var_data_list = VarData(hooks=["what"]) + var_data_dict = VarData(hooks={"what": None}) + assert var_data_str == var_data_list == var_data_dict + + var_data_list_multiple = VarData(hooks=["what", "whot"]) + var_data_dict_multiple = VarData(hooks={"what": None, "whot": None}) + assert var_data_list_multiple == var_data_dict_multiple + + +def test_var_data_with_hooks_value(): + var_data = VarData(hooks={"what": VarData(hooks={"whot": VarData(hooks="whott")})}) + assert var_data == VarData(hooks=["what", "whot", "whott"]) diff --git a/tests/units/utils/test_format.py b/tests/units/utils/test_format.py index 2a2aa8259..89197a03e 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 @@ formatted_router = { "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 @@ formatted_router = { }, ), ( - 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 f8573111c..44356dac5 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) @@ -122,13 +122,13 @@ def test_validate_invalid_bun_path(mocker): Args: mocker: Pytest mocker object. """ - mock = mocker.Mock() - mocker.patch.object(mock, "bun_path", return_value="/mock/path") - mocker.patch("reflex.utils.prerequisites.get_config", mock) + mock_path = mocker.Mock() + mocker.patch("reflex.utils.path_ops.get_bun_path", return_value=mock_path) mocker.patch("reflex.utils.prerequisites.get_bun_version", return_value=None) with pytest.raises(typer.Exit): prerequisites.validate_bun() + mock_path.samefile.assert_called_once() def test_validate_bun_path_incompatible_version(mocker): @@ -137,9 +137,8 @@ def test_validate_bun_path_incompatible_version(mocker): Args: mocker: Pytest mocker object. """ - mock = mocker.Mock() - mocker.patch.object(mock, "bun_path", return_value="/mock/path") - mocker.patch("reflex.utils.prerequisites.get_config", mock) + mock_path = mocker.Mock() + mocker.patch("reflex.utils.path_ops.get_bun_path", return_value=mock_path) mocker.patch( "reflex.utils.prerequisites.get_bun_version", return_value=version.parse("0.6.5"), @@ -587,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: diff --git a/tests/units/vars/test_base.py b/tests/units/vars/test_base.py index 68bc0c38e..e4ae7327a 100644 --- a/tests/units/vars/test_base.py +++ b/tests/units/vars/test_base.py @@ -1,4 +1,4 @@ -from typing import Dict, List, Union +from typing import List, Mapping, Union import pytest @@ -37,12 +37,12 @@ class ChildGenericDict(GenericDict): ("a", str), ([1, 2, 3], List[int]), ([1, 2.0, "a"], List[Union[int, float, str]]), - ({"a": 1, "b": 2}, Dict[str, int]), - ({"a": 1, 2: "b"}, Dict[Union[int, str], Union[str, int]]), + ({"a": 1, "b": 2}, Mapping[str, int]), + ({"a": 1, 2: "b"}, Mapping[Union[int, str], Union[str, int]]), (CustomDict(), CustomDict), (ChildCustomDict(), ChildCustomDict), - (GenericDict({1: 1}), Dict[int, int]), - (ChildGenericDict({1: 1}), Dict[int, int]), + (GenericDict({1: 1}), Mapping[int, int]), + (ChildGenericDict({1: 1}), Mapping[int, int]), ], ) def test_figure_out_type(value, expected):